在namedtuple中输入提示

问题描述 投票:79回答:2

请考虑以下代码:

from collections import namedtuple
point = namedtuple("Point", ("x:int", "y:int"))

上面的代码只是一种证明我想要实现的目标的方法。我想用类型提示制作namedtuple

你知道如何达到预期效果的优雅方式吗?

python python-3.x type-hinting namedtuple python-dataclasses
2个回答
78
投票

从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)

86
投票

你可以使用typing.NamedTuple

来自文档

namedtuple的打字版本。

>>> import typing
>>> Point = typing.NamedTuple("Point", [('x', int), ('y', int)])

这只出现在Python 3.5之后

© www.soinside.com 2019 - 2024. All rights reserved.