最佳答案
当我想在 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]):