Adds a __repr__ to graph.
[pyutils.git] / src / pyutils / typez / type_utils.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2023, 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     Raises:
27         AssertionError: the parameter is, indeed, of NoneType.
28
29     >>> x: Optional[bool] = True
30     >>> unwrap_optional(x)
31     True
32
33     >>> y: Optional[str] = None
34     >>> unwrap_optional(y)
35     Traceback (most recent call last):
36     ...
37     AssertionError: Argument to unwrap_optional was unexpectedly None
38     """
39     if x is None:
40         msg = 'Argument to unwrap_optional was unexpectedly None'
41         logger.critical(msg)
42         raise AssertionError(msg)
43     return x
44
45
46 if __name__ == '__main__':
47     import doctest
48
49     doctest.testmod()