我有一个函数可以接受任何可以索引的变量作为输入,例如元组列表。如何在函数的类型提示中指明这一点?
答案 0 :(得分:12)
您的方法正在接受sequence,因此请使用typing.Sequence
。这是通用的,因此您可以指定序列必须包含的对象类型:
from typing import Sequence
def foo(bar: Sequence[int]):
# bar is a sequence of integers
一个iterable,它通过
__getitem__()
特殊方法使用整数索引支持有效的元素访问,并定义一个返回序列长度的__len__()
方法。一些内置序列类型为list
,str
,tuple
和bytes
。