Using List / Tuple / etc. from vs input of a directly referencing type as list / tuple / etc

What is the difference between using List , Tuple , etc. from typing module:

 from typing import Tuple def f(points: Tuple): return map(do_stuff, points) 

Unlike directly calling Python types:

 def f(points: tuple): return map(do_stuff, points) 

And when should I use one over the other?

+7
python type-hinting typing
source share
1 answer

typing.Tuple and typing.List Common types ; this means that you can specify what type of content should be:

 def f(points: Tuple[float, float]): return map(do_stuff, points) 

This indicates that the passed tuple should contain two float values. You cannot do this with the built-in type tuple .

typing.Tuple is a feature here, since it allows you to specify a certain number of expected elements and the type of each position. Use an ellipsis if no length is specified and the type must be repeated: Tuple[float, ...] describes a variable length tuple with float s.

For typing.List and other types of sequences, you usually specify a type for all elements; List[str] - a list of strings of any size. Note that functions should predominantly accept type.Sequence as arguments, and typing.List usually used only for return types; generally speaking, most functions would perform any sequence and only iterate, but when you return list , you really return a specific, mutable type of sequence.

You should always choose typing generators, even if you are not currently restricting the content. It is easier to add this restriction later with a typical type, since the resulting change will be less.

+19
source share

All Articles