什么类型提示包含列表和元组?

时间:2017-02-27 12:37:34

标签: python python-3.x type-hinting

我有一个函数可以接受任何可以索引的变量作为输入,例如元组列表。如何在函数的类型提示中指明这一点?

1 个答案:

答案 0 :(得分:12)

您的方法正在接受sequence,因此请使用typing.Sequence。这是通用的,因此您可以指定序列必须包含的对象类型:

from typing import Sequence

def foo(bar: Sequence[int]):
    # bar is a sequence of integers

引用Python glossary

  

一个iterable,它通过__getitem__()特殊方法使用整数索引支持有效的元素访问,并定义一个返回序列长度的__len__()方法。一些内置序列类型为liststrtuplebytes