Add a doctest to type_utils.py.
[python_utils.git] / type_utils.py
1 #!/usr/bin/env python3
2
3 import logging
4 from typing import Any, Optional
5
6 logger = logging.getLogger(__name__)
7
8
9 def unwrap_optional(x: Optional[Any]) -> Any:
10     """Unwrap an Optional[Type] argument returning a Type value back.
11     If the Optional[Type] argument is None, however, raise an exception.
12     Use this to satisfy most type checkers that a value that could
13     be None isn't so as to drop the Optional typing hint.
14
15     >>> x: Optional[bool] = True
16     >>> unwrap_optional(x)
17     True
18
19     >>> y: Optional[str] = None
20     >>> unwrap_optional(y)
21     Traceback (most recent call last):
22     ...
23     AssertionError: Argument to unwrap_optional was unexpectedly None
24
25     """
26     if x is None:
27         msg = 'Argument to unwrap_optional was unexpectedly None'
28         logger.critical(msg)
29         raise AssertionError(msg)
30     return x
31
32
33 if __name__ == '__main__':
34     import doctest
35
36     doctest.testmod()