How to check a variable against Union type during runtime?
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, (<class ‘int’>, <class … Read more