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