python - 如何为 Mypy 类型注释指定 OrderedDict K,V 类型?

标签 python python-3.5 type-hinting mypy

我正在使用 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 中没有)。 但是 Python 3.6.0 存在问题。 考虑以下几点:

from collections import OrderedDict
from typing import Dict

def foo() -> Dict[str, int]:
    result: OrderedDict[str, int] = OrderedDict()
    result['two'] = 2
    return result

此代码将同时满足 mypy (0.501) 和 Python (3.6.0)。 但是,如果将 Dict 替换为 OrderedDict,那么 mypy 仍然会很高兴,但执行它会因 TypeError: 'type' object is not subscriptable.

有趣的是,Python 解释器在函数签名中看到下标 OrderedDict 时会死掉,但很高兴在变量类型注释中接受它。

无论如何,我的解决方法是在函数签名中使用 Dict 而不是 OrderedDict (并添加注释,如果/当Python 解释器将学会接受正确的签名)。

关于python - 如何为 Mypy 类型注释指定 OrderedDict K,V 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41207128/

相关文章:

python - 如何遍历字典列表

flask - 如何使用 pytest-flask 将发布数据发送到 flask

python 3.5.1 : NameError: name 'json' is not defined

python - 从Python文件中读取二维数组

python - 如何导入模块 PyImgur Python

python - 检测 OCR 标记

python - 如何在 Python 中创建用户定义类型断言?

python - 带有 br 标签的 Beautifulsoup 兄弟结构

python - 使用 typing 模块时如何检查类型兼容性?

python - "void"函数中的 NoReturn 与 None - Python 3.6 中的类型注释