【发布时间】:2017-05-03 14:12:41
【问题描述】:
我正在使用 Python 3.5 和 Mypy 对我的脚本进行一些基本的静态检查。最近我重构了一些返回 OrderedDict 的方法,但是当我尝试使用指定了 Key 和 Value 类型的返回注解时遇到了“'type' object is not subscriptable”错误。
简化示例:
#!/usr/bin/env python3.5
from collections import OrderedDict
# this works
def foo() -> OrderedDict:
result = OrderedDict() # type: OrderedDict[str, int]
result['foo'] = 123
return result
# this doesn't
def foo2() -> OrderedDict[str, int]:
result = OrderedDict() # type: OrderedDict[str, int]
result['foo'] = 123
return result
print(foo())
这是运行时的python输出:
Traceback (most recent call last):
File "./foo.py", line 12, in <module>
def foo2() -> OrderedDict[str, int]:
TypeError: 'type' object is not subscriptable
然而,Mypy 对注释中的类型注释没有问题,如果我尝试执行 result[123] = 123,实际上会发出警告。
这是什么原因造成的?
【问题讨论】:
-
现在可以使用(mypy 版本 0.501)。
-
仅存入修复链接:bugs.python.org/issue35341
标签: python python-3.5 type-hinting mypy