I have a function that can accept as input any variable that can be indexed, such as a list or a tuple. How do I indicate this in the type-hint of the function?
In Python, list and tuple are a class of data structures that can store one or more objects or values. A list is used to store multiple items in one variable and can be created using square brackets. Similarly, tuples also can store multiple items in a single variable and can be declared using parentheses.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.
Code insight: Type Annotations for list, set, tuple, frozenset in Python 3.9 insert from typing import ... Hit Alt+Enter on data and select "Add type hint for variable data ". So Code Insight behaves correctly adding lowercase letter tuple .
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 arelist
,str
,tuple
, andbytes
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With