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)
但它没有帮助修复引发的错误.
我该怎么做才能纠正这个错误?谢谢.
如果你想让mypy理解你的命名元素的样子,你应该NamedTuple从typing模块中导入,如下所示:
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目前没有任何规定在类型检查阶段传播或提取任何给定变量的实际值.
以完全一般的方式实现这一点实际上非常具有挑战性,因此不太可能很快添加此功能(如果是这样,它可能会以更加有限的形式).
| 归档时间: |
|
| 查看次数: |
816 次 |
| 最近记录: |