3 # © Copyright 2021-2023, Scott Gasch
5 """Utility functions for dealing with typing."""
8 from typing import Any, Optional
10 logger = logging.getLogger(__name__)
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.
19 x: an Optional[Type] argument
22 If the Optional[Type] argument is non-None, return it.
23 If the Optional[Type] argument is None, however, raise an
27 AssertionError: the parameter is, indeed, of NoneType.
29 >>> x: Optional[bool] = True
30 >>> unwrap_optional(x)
33 >>> y: Optional[str] = None
34 >>> unwrap_optional(y)
35 Traceback (most recent call last):
37 AssertionError: Argument to unwrap_optional was unexpectedly None
40 msg = 'Argument to unwrap_optional was unexpectedly None'
42 raise AssertionError(msg)
46 if __name__ == '__main__':