Pav*_*ari 100 python type-hinting namedtuple python-3.x python-dataclasses
请考虑以下代码:
from collections import namedtuple
point = namedtuple("Point", ("x:int", "y:int"))
Run Code Online (Sandbox Code Playgroud)
上面的代码只是一种证明我想要实现的目标的方法.我想namedtuple用类型提示.
你知道如何达到预期效果的优雅方式吗?
Wol*_*ehn 105
从3.6开始的类型命名元组的首选语法是
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int = 1 # Set default value
Point(3) # -> Point(x=3, y=1)
Run Code Online (Sandbox Code Playgroud)
编辑 启动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)
Run Code Online (Sandbox Code Playgroud)
Bha*_*Rao 95
您可以使用 typing.NamedTuple
来自文档
类型版本的
namedtuple.
>>> import typing
>>> Point = typing.NamedTuple("Point", [('x', int), ('y', int)])
Run Code Online (Sandbox Code Playgroud)
这只出现在Python 3.5之后
mrv*_*vol 15
公平地说,NamedTuple来自typing:
>>> from typing import NamedTuple
>>> class Point(NamedTuple):
... x: int
... y: int = 1 # Set default value
...
>>> Point(3)
Point(x=3, y=1)
Run Code Online (Sandbox Code Playgroud)
等于经典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)
Run Code Online (Sandbox Code Playgroud)
所以,NamedTuple这只是语法糖namedtuple
NamedTuple下面,您可以从 的源代码中找到一个创建函数python 3.10。正如我们所看到的,它使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21163 次 |
| 最近记录: |