What type-hint contains both list and tuple?

我与影子孤独终老i 提交于 2021-02-07 04:48:14

问题


I have a function that can accept as input any variable that can be indexed, such as a list of a tuple. How do I indicate this in the type-hint of the function?


回答1:


Your method is accepting a sequence, so use typing.Sequence. That's a generic, so you can specify what type of object(s) the sequence must contain:

from typing import Sequence

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

Quoting the Python glossary:

An iterable which supports efficient element access using integer indices via the __getitem__() special method and defines a __len__() method that returns the length of the sequence. Some built-in sequence types are list, str, tuple, and bytes.



来源:https://stackoverflow.com/questions/42486006/what-type-hint-contains-both-list-and-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!