Check a variable against Union type at runtime in Python 3.6

后端 未结 4 1250
春和景丽
春和景丽 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

    You could use the __args__ attribute of Union which holds a tuple of the "possible contents:

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

    The __args__ argument is not documented so it could be considered "messing with implementation details" but it seems like a better way than parsing the repr.

提交回复
热议问题