Richard Hansen Richard Hansen - 11 months ago 54
Python Question

How to annotate types of multiple return values?

How do I use type hints to annotate a function that returns an

that always yields two values: a
and a
? The hint
Tuple[bool, str]
is close, except that it limits the return value type to a tuple, not a generator or other type of iterable.

I'm mostly curious because I would like to annotate a function
that is used to return multiple values like this:

always_a_bool, always_a_str = foo()

Usually functions like
do something like
return a, b
(which returns a tuple), but I would like the type hint to be flexible enough to replace the returned tuple with a generator or list or something else.

Answer Source

You are always returning one object; using return one, two simply returns a tuple.

So yes, -> Tuple[bool, str] is entirely correct.

Only the Tuple type lets you specify a fixed number of elements, each with a distinct type. You really should be returning a tuple, always, if your function produces a fixed number of return values, especially when those values are specific, distinct types.

Other sequence types are expected to have one type specification for a variable number of elements, so typing.Sequence is not suitable here. Also see What's the difference between list and tuples?

Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.

Python's type hint system adheres to that philosophy, there is currently no syntax to specify an iterable of fixed length and containing specific types at specific positions.

If you must specify that any iterable will do, then the best you can do is:

-> Iterable[Union[bool, str]]

at which point the caller can expect booleans and strings in any order, and of unknown length (anywhere between 0 and infinity).