X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;ds=sidebyside;f=type_utils.py;h=5e4187ec03658de957983a705349dda80876cd6d;hb=532df2c5b57c7517dfb3dddd8c1358fbadf8baf3;hp=ee52444e7828c1d2b7920749a800dbf77e653983;hpb=709370b2198e09f1dbe195fe8813602a3125b7f6;p=python_utils.git diff --git a/type_utils.py b/type_utils.py index ee52444..5e4187e 100644 --- a/type_utils.py +++ b/type_utils.py @@ -1,5 +1,9 @@ #!/usr/bin/env python3 +# © Copyright 2021-2022, Scott Gasch + +"""Utility functions for dealing with typing.""" + import logging from typing import Any, Optional @@ -10,10 +14,27 @@ 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. + 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()