我将使用Python 3.5和Mypy对我的脚本进行一些基本的静态检查。最近,我重构了一些方法以返回OrderedDict,但在尝试使用带有指定的键和值类型的返回注释时遇到了“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
,它实际上会发出警告。
这是什么原因?
目前没有回答
相关问题 更多 >
编程相关推荐