We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data.
You can return multiple values from a function using either a dictionary, a tuple, or a list. These data types all let you store multiple values.
Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.
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 lists 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).
Last but not least, as of Python 3.9, you can use
-> tuple[bool, str]
instead of -> Tuple[bool, str]
; support for type hinting notation has been added to most standard-library container types (see PEP 585 for the complete list). In fact, you can use this as of Python 3.7 too provided you use the from __future__ import annotations
compiler switch for your modules and a type checker that supports the syntax.
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