在 Python 中键入提示元组
TypeHinting tuples in Python
当我想在 Python 中键入一个元组提示时,例如:
def func(var: tuple[int, int]):
# do something
func((1, 2)) # would be fine
func((1, 2, 3)) # would throw an error
需要给出元组中项目的确切数量。这与列表类型提示不同:
def func(var: list[int]):
# do something
func([1]) # would be fine
func([1, 2]) # would also be fine
func([1, 2, 3]) # would also be fine
在某种程度上,这是必然的,因为元组的类型。因为它们被设计为不可更改,所以您必须对其中的项目数量进行硬编码。
所以我的问题是,有没有办法使元组类型提示中的项数灵活?我尝试过类似的方法,但没有用:
def func(var: tuple[*int]):
是的,您可以使元组类型提示中的项数灵活:
from typing import Tuple
def func(var: Tuple[int, ...]):
pass
来自文档:https://docs.python.org/3/library/typing.html#typing.Tuple
To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, ...]
. A plain Tuple
is equivalent to Tuple[Any, ...]
, and in turn to tuple
.
从 PEP 585 开始,可以在不导入 typing
模块的情况下使用内置类型,因此从 Python 3.9 开始,Tuple[...]
已被弃用,取而代之的是tuple[...]
。例如
def func(var: tuple[int, ...]):
pass
当我想在 Python 中键入一个元组提示时,例如:
def func(var: tuple[int, int]):
# do something
func((1, 2)) # would be fine
func((1, 2, 3)) # would throw an error
需要给出元组中项目的确切数量。这与列表类型提示不同:
def func(var: list[int]):
# do something
func([1]) # would be fine
func([1, 2]) # would also be fine
func([1, 2, 3]) # would also be fine
在某种程度上,这是必然的,因为元组的类型。因为它们被设计为不可更改,所以您必须对其中的项目数量进行硬编码。
所以我的问题是,有没有办法使元组类型提示中的项数灵活?我尝试过类似的方法,但没有用:
def func(var: tuple[*int]):
是的,您可以使元组类型提示中的项数灵活:
from typing import Tuple
def func(var: Tuple[int, ...]):
pass
来自文档:https://docs.python.org/3/library/typing.html#typing.Tuple
To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g.
Tuple[int, ...]
. A plainTuple
is equivalent toTuple[Any, ...]
, and in turn totuple
.
从 PEP 585 开始,可以在不导入 typing
模块的情况下使用内置类型,因此从 Python 3.9 开始,Tuple[...]
已被弃用,取而代之的是tuple[...]
。例如
def func(var: tuple[int, ...]):
pass