Код: Выделить всё
import typing
typ = typing.Union[int, str]
if issubclass(typ, typing.Union):
print('value type should be one of', typ.__args__)
elif issubclass(typ, typing.Generic):
print('value type should be a structure of', typ.__args__[0])
else:
print('value type should be', typ)
Код: Выделить всё
Traceback (most recent call last):
File "untitled.py", line 6, in
if issubclass(typ, typing.Union):
File "C:\Python34\lib\site-packages\typing.py", line 829, in __subclasscheck__
raise TypeError("Unions cannot be used with issubclass().")
TypeError: Unions cannot be used with issubclass().
Код: Выделить всё
isinstanceКод: Выделить всё
>>> isinstance(typ, typing.Union)
Traceback (most recent call last):
File "", line 1, in
File "C:\Python34\lib\site-packages\typing.py", line 826, in __instancecheck__
raise TypeError("Unions cannot be used with isinstance().")
TypeError: Unions cannot be used with isinstance().
Если возможно, я хотел бы увидеть решение, подкрепленное документацией, PEP или каким-либо другим ресурсом. Легко найти «решение», которое «работает» за счет доступа к недокументированным внутренним атрибутам. Но, скорее всего, это окажется деталью реализации и изменится в будущих версиях. Я ищу "правильный способ", чтобы сделать это.
Подробнее здесь: https://stackoverflow.com/questions/491 ... ng-generic