在 namedtuple 中键入提示
Type hints in namedtuple
考虑以下代码:
from collections import namedtuple
point = namedtuple("Point", ("x:int", "y:int"))
上面的代码只是展示我正在努力实现的目标的一种方式。
我想用类型提示制作 namedtuple
。
您知道如何以优雅的方式实现预期的结果吗?
您可以使用typing.NamedTuple
来自文档
Typed version of 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 开始,考虑使用 dataclasses
(您的 IDE 可能还不支持它们进行静态类型检查):
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int = 1 # Set default value
Point(3) # -> Point(x=3, y=1)
为了公平起见,NamedTuple
来自 typing
:
>>> 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
考虑以下代码:
from collections import namedtuple
point = namedtuple("Point", ("x:int", "y:int"))
上面的代码只是展示我正在努力实现的目标的一种方式。
我想用类型提示制作 namedtuple
。
您知道如何以优雅的方式实现预期的结果吗?
您可以使用typing.NamedTuple
来自文档
Typed version of
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 开始,考虑使用 dataclasses
(您的 IDE 可能还不支持它们进行静态类型检查):
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int = 1 # Set default value
Point(3) # -> Point(x=3, y=1)
为了公平起见,NamedTuple
来自 typing
:
>>> 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