Check a variable against Union type at runtime in Python 3.6

后端 未结 4 1238
春和景丽
春和景丽 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 01:54

    In Python 3.8 and later, the approach suggested by MSeifert and Richard Xia can be improved by not using the undocumented attributes __origin__ and __args__. This functionality is provided by the new functions typing.get_args(tp) and typing.get_origin(tp):

    >> from typing import Union, get_origin, get_args
    >> x = Union[int, str]
    >> get_origin(x), get_args(x)
    (typing.Union, (, ))
    >> get_origin(x) is Union
    True
    >> isinstance(3, get_args(x))
    True
    >> isinstance('a', get_args(x))
    True
    >> isinstance([], get_args(x))
    False
    

    P.S.: I know that the question is about Python 3.6 (probably because this was the newest version at the time), but I arrived here when I searched for a solution as a Python 3.8 user. I guess that others might be in the same situation, so I thought that adding a new answer here makes sense.

提交回复
热议问题