Check a variable against Union type at runtime in Python 3.6

后端 未结 4 1253
春和景丽
春和景丽 2020-12-10 01:36

UPDATE (September 2020): Python 3.9 includes the typing.get_type_hints function for this use case, see https://docs.python.org/3.9/library/typ

4条回答
  •  渐次进展
    2020-12-10 02:09

    You can use the typeguard module which can be installed with pip. It provides you with a function check_argument_types or a function decorator @typechecked. which should do your runtime type checking for you: https://github.com/agronholm/typeguard

    from typing import Union
    from typeguard import check_argument_types, typechecked
    
    def check_and_do_stuff(a: Union[str, int]) -> None:
        check_argument_types() 
        # do stuff ...
    
    @typechecked
    def check_decorator(a: Union[str, int]) -> None:
        # do stuff ...
    
    check_and_do_stuff("hello")
    check_and_do_stuff(42)
    check_and_do_stuff(3.14)  # raises TypeError
    

    If you want to check a type of a single variable for a different reason, you can use typeguard's check_type function directly:

    from typing import Union
    from typeguard import check_type
    
    MyType = Union[str, int]
    
    check_type("arg", "string", MyType, None)  # OK
    check_type("arg", 42, MyType, None)  # OK
    check_type("arg", 3.5, MyType, None)  # raises TypeError
    

    The "arg" and None arguments are unused in this example. Note that the check_type function is not documented as a public function of this module so its API may be subject to change.

提交回复
热议问题