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