Python 在命名元组中键入提示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34269772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:43:23  来源:igfitidea点击:

Type hints in namedtuple

pythonpython-3.xtype-hintingnamedtuplepython-dataclasses

提问by Pavel Hanpari

Consider following piece of code:

考虑以下代码:

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

The Code above is just a way to demonstrate as to what I am trying to achieve. I would like to make namedtuplewith type hints.

上面的代码只是展示我想要实现的目标的一种方式。我想namedtuple使用类型提示进行制作。

Do you know any elegant way how to achieve result as intended?

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

采纳答案by Wolfgang Kuehn

The prefered Syntax for a typed named tuple since 3.6 is

自 3.6 以来类型化命名元组的首选语法是

from typing import NamedTuple

class Point(NamedTuple):
    x: int
    y: int = 1  # Set default value

Point(3)  # -> Point(x=3, y=1)

EditStarting Python 3.7, consider using dataclasses(your IDE may not yet support them for static type checking):

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

回答by Bhargav Rao

You can use typing.NamedTuple

您可以使用 typing.NamedTuple

From the docs

从文档

Typed versionof namedtuple.

类型版本namedtuple

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

This is present only in Python 3.5 onwards

这仅存在于 Python 3.5 以上