How to annotate multiple return types?

How to use type hints to annotate a function that returns Iterable , which always gives two values: a bool and a str ? The Tuple[bool, str] tip is close, except that it restricts the return type to a tuple, rather than a generator or other type of iteration.

I am most curious because I would like to annotate the foo() function, which is used to return multiple values, such as:

 always_a_bool, always_a_str = foo() 

Usually functions like foo() 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.

+6
source share
1 answer

You always return one object; using return one, two just returns the tuple.

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

Only the Tuple type allows you to specify a fixed number of elements, each of which has a separate type. You really should return a tuple, always if your function creates a fixed number of returned values, especially when these values ​​are concrete, different types.

It is assumed that other types of sequences will have one type specification for a variable number of elements, so typing.Sequence is not suitable here. Also see What is the difference between lists and tuples?

Tuples are heterogeneous data structures (i.e., their records have different meanings), and lists are homogeneous sequences. Tuples have a structure, lists have an order.

The Python type hint system adheres to this philosophy; there is currently no syntax for specifying iterations of a fixed length and containing certain types in certain positions.

If you must indicate what any iterative will do, then the best you can do is:

 -> Iterable[Union[bool, str]] 

at this point, the caller can expect logical lines and lines in any order and of unknown length (somewhere between 0 and infinity).

+11
source

Source: https://habr.com/ru/post/1011561/


All Articles