考虑下面这段代码:
from collections import namedtuple
point = namedtuple("Point", ("x:int", "y:int"))
上面的代码只是一种方式来演示我想要达到的目标。 我想让namedtuple类型提示。
你知道有什么优雅的方法可以达到预期的效果吗?
考虑下面这段代码:
from collections import namedtuple
point = namedtuple("Point", ("x:int", "y:int"))
上面的代码只是一种方式来演示我想要达到的目标。 我想让namedtuple类型提示。
你知道有什么优雅的方法可以达到预期的效果吗?
你可以使用打字。NamedTuple
来自文档
namedtuple的类型化版本。
>>> import typing
>>> Point = typing.NamedTuple("Point", [('x', int), ('y', int)])
这只在Python 3.5以后才有
自3.6以来,类型化命名元组的首选语法是
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int = 1 # Set default value
Point(3) # -> Point(x=3, y=1)
编辑 从Python 3.7开始,考虑使用数据类(你的IDE可能还不支持它们进行静态类型检查):
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int = 1 # Set default value
Point(3) # -> Point(x=3, y=1)
为了公平起见,NamedTuple从输入:
>>> from typing import NamedTuple
>>> class Point(NamedTuple):
... x: int
... y: int = 1 # Set default value
...
>>> Point(3)
Point(x=3, y=1)
等于经典的namedtuple:
>>> from collections import namedtuple
>>> p = namedtuple('Point', 'x,y', defaults=(1, ))
>>> p.__annotations__ = {'x': int, 'y': int}
>>> p(3)
Point(x=3, y=1)
NamedTuple只是NamedTuple的语法糖
下面,你可以从python 3.10的源代码中找到一个创建NamedTuple函数。如我们所见,它使用collections.namedtuple构造函数,并从提取的类型中添加__annotations__:
def _make_nmtuple(name, types, module, defaults = ()):
fields = [n for n, t in types]
types = {n: _type_check(t, f"field {n} annotation must be a type")
for n, t in types}
nm_tpl = collections.namedtuple(name, fields,
defaults=defaults, module=module)
nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types
return nm_tpl