[Tutor] What is Tuple in the typing module?
Peter Otten
__peter__ at web.de
Sat Aug 17 05:36:24 EDT 2019
C W wrote:
> Hi everyone,
>
> What exactly is Tuple in the typing module? What does it do?
>
> This is the definition from its website.
> https://docs.python.org/3/library/typing.html
> "A type alias is defined by assigning the type to the alias"
>
> I have no idea what that means.
>
> Here's the example from the documentation:
>
> from typing import Dict, Tuple, Sequence
> ConnectionOptions = Dict[str, str]Address = Tuple[str, int]Server =
> Tuple[Address, ConnectionOptions]
> def broadcast_message(message: str, servers: Sequence[Server]) -> None:
> ...
> # The static type checker will treat the previous type signature as#
> being exactly equivalent to this one.def broadcast_message(
> message: str,
> servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) ->
> None:
> ...
>
>
> I think this even more confusing. Can someone explain this in simple
> words? I don't have a intense computer science background.
After the line
ANSWER = 42
you can write
print("The answer is", ANSWER)
rather than
print("The answer is", 42)
Likewise, after
Location = Tuple[float, float, float]
"Location" has become an "alias" for a tuple of 3 floats, and you can write
def distance(a: Location, b: Location) --> float: ...
instead of
def distance(
a: Tuple[float, float, float],
b: Tuple[float, float, float]
) --> float: ...
Basically, use descriptive names for types rather than repeating their
definition.
More information about the Tutor
mailing list