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]):
46977 次浏览

Yes, you can make the number of items in a tuple type hint flexible:

from typing import Tuple


def func(var: Tuple[int, ...]):
pass

From the docs: 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.

Starting with PEP 585 it is possible to use builtin typings without importing the typing module, so starting with Python 3.9, Tuple[...] has been deprecated in favor of tuple[...]. e.g.

def func(var: tuple[int, ...]):
pass