mypy错误:作为namedtuple()的第二个参数的list或tuple literal

Yuv*_*uss 2 python typing type-hinting python-3.x mypy

我写了一个代码python 3.5,看起来像这样:

from collections import namedtuple

attributes = ('content', 'status')
Response = namedtuple('Response', attributes)
Run Code Online (Sandbox Code Playgroud)

然后我运行mypy类型检查器来分析这段代码.mypy提出这个错误:

test.py:4:error:作为第二个参数的List或tuple literal namedtuple()

我试图在attributes变量中添加一个类型注释:

from typing import Tuple
attributes = ('content', 'status')  # type: Tuple[str, str]
Run Code Online (Sandbox Code Playgroud)

但它没有帮助修复引发的错误.

我该怎么做才能纠正这个错误?谢谢.

Mic*_*x2a 6

如果你想让mypy理解你的命名元素的样子,你应该NamedTupletyping模块中导入,如下所示:

from typing import NamedTuple

Response = NamedTuple('Response', [('content', str), ('status', str)])
Run Code Online (Sandbox Code Playgroud)

然后,您可以Response像任何其他命名元组一样使用,除了mypy现在了解每个单独字段的类型.如果您使用的是Python 3.6,则还可以使用替代的基于类的语法:

from typing import NamedTuple

class Response(NamedTuple):
    content: str
    status: str
Run Code Online (Sandbox Code Playgroud)

如果你希望动态地改变字段并编写一些可以在运行时"构建"不同的命名元组的东西,那么遗憾的是在Python的类型生态系统中是不可能的.PEP 484目前没有任何规定在类型检查阶段传播或提取任何给定变量的实际.

以完全一般的方式实现这一点实际上非常具有挑战性,因此不太可能很快添加此功能(如果是这样,它可能会以更加有限的形式).

  • @JimFasarakisHilliard - 未来可能会更像是一件事!Guido显然对修改Python本身感兴趣,因此你可以用这种风格定义自定义类(没有所有的namedtuple开销,也不必编写`__init__`方法) - 参见[this post](https:// mail.来自python-ideas邮件列表的python.org/pipermail/python-ideas/2017-May/045654.html)以及一些后续的邮件列表.讨论部分受到[attrs library](https://github.com/python-attrs/attrs)的启发,显然非常受欢迎. (2认同)