Easier and more self documenting patterns for loading/saving Persistent
[python_utils.git] / type_utils.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2022, Scott Gasch
4
5 """Utility functions for dealing with typing."""
6
7 import logging
8 from typing import Any, Optional
9
10 logger = logging.getLogger(__name__)
11
12
13 def unwrap_optional(x: Optional[Any]) -> Any:
14     """Unwrap an Optional[Type] argument returning a Type value back.
15     Use this to satisfy most type checkers that a value that could be
16     None isn't so as to drop the Optional typing hint.
17
18     Args:
19         x: an Optional[Type] argument
20
21     Returns:
22         If the Optional[Type] argument is non-None, return it.
23         If the Optional[Type] argument is None, however, raise an
24         exception.
25
26     >>> x: Optional[bool] = True
27     >>> unwrap_optional(x)
28     True
29
30     >>> y: Optional[str] = None
31     >>> unwrap_optional(y)
32     Traceback (most recent call last):
33     ...
34     AssertionError: Argument to unwrap_optional was unexpectedly None
35     """
36     if x is None:
37         msg = 'Argument to unwrap_optional was unexpectedly None'
38         logger.critical(msg)
39         raise AssertionError(msg)
40     return x
41
42
43 if __name__ == '__main__':
44     import doctest
45
46     doctest.testmod()