Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type-hint contains both list and tuple?

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?

like image 453
Erel Segal-Halevi Avatar asked Feb 27 '17 12:02

Erel Segal-Halevi


People also ask

Are list and tuple data types?

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.

What is typing tuple in Python?

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.

How do you write a hint tuple?

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 .


1 Answers

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.

like image 127
Martijn Pieters Avatar answered Oct 12 '22 13:10

Martijn Pieters