X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=type_utils.py;h=1584597c039bc6a78900f28e3182ed64e601059d;hb=d2357ff35e7752ae3eb6caa2813c35c17fea778b;hp=7b79af08f934f0b93153c5c14065a3a884de9a91;hpb=497fb9e21f45ec08e1486abaee6dfa7b20b8a691;p=python_utils.git diff --git a/type_utils.py b/type_utils.py index 7b79af0..1584597 100644 --- a/type_utils.py +++ b/type_utils.py @@ -7,8 +7,30 @@ logger = logging.getLogger(__name__) def unwrap_optional(x: Optional[Any]) -> Any: + """Unwrap an Optional[Type] argument returning a Type value back. + If the Optional[Type] argument is None, however, raise an exception. + Use this to satisfy most type checkers that a value that could + be None isn't so as to drop the Optional typing hint. + + >>> 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()