【发布时间】:2017-08-14 01:10:30
【问题描述】:
这段代码:
#!/usr/bin/env python
from typing import Optional, Type
class Foo(object):
pass
class Bar(Foo):
pass
def test_me() -> Optional[Type[Foo]]:
print("Hi there!")
return Bar
if __name__ == "__main__":
test_me()
将在 3.5.2 上提高 TypeError:
Traceback (most recent call last):
File "./test.py", line 11, in <module>
def test_me() -> Optional[Type[Foo]]:
File "/Users/mnot/.pyenv/versions/3.5.2/lib/python3.5/typing.py", line 649, in __getitem__
return Union[arg, type(None)]
File "/Users/mnot/.pyenv/versions/3.5.2/lib/python3.5/typing.py", line 552, in __getitem__
dict(self.__dict__), parameters, _root=True)
File "/Users/mnot/.pyenv/versions/3.5.2/lib/python3.5/typing.py", line 512, in __new__
for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
File "/Users/mnot/.pyenv/versions/3.5.2/lib/python3.5/typing.py", line 512, in <genexpr>
for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
File "/Users/mnot/.pyenv/versions/3.5.2/lib/python3.5/typing.py", line 1077, in __subclasscheck__
if super().__subclasscheck__(cls):
File "/Users/mnot/.pyenv/versions/3.5.2/lib/python3.5/abc.py", line 225, in __subclasscheck__
for scls in cls.__subclasses__():
TypeError: descriptor '__subclasses__' of 'type' object needs an argument
而它在 3.6 上运行良好。如果我将 Optional 拼写为 Union[None, Type[Foo]],也会出现同样的问题。
对于 3.5.2 是否有任何解决方法,同时仍能准确地注释返回类型?
【问题讨论】:
标签: python python-3.x annotations python-3.5 typing