如何为Mypy类型注释指定OrderDict键,值类型?

2024-05-17 11:35:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我将使用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,它实际上会发出警告。

这是什么原因?


Tags: 类型returnobjectfooisdeftypenot