【发布时间】:2018-08-16 16:37:52
【问题描述】:
我正在尝试编写验证类型提示的代码,为此我必须找出注释的对象类型。例如,考虑这个应该告诉用户期望什么样的值的 sn-p:
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)
这应该打印“值类型应该是(int,str)之一”,但它会抛出异常:
Traceback (most recent call last):
File "untitled.py", line 6, in <module>
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 "<stdin>", line 1, in <module>
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().
检查typ 是否为typing.Generic 的正确方法是什么?
如果可能的话,我希望看到一个由文档或 PEP 或其他资源支持的解决方案。通过访问未记录的内部属性来“工作”的“解决方案”很容易找到.但更有可能的是,它会变成一个实现细节,并且会在未来的版本中发生变化。我正在寻找“正确的方法”。
【问题讨论】:
标签: python generics type-hinting