【发布时间】:2018-05-12 00:58:42
【问题描述】:
当我想在 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]):
【问题讨论】:
标签: python type-hinting