Types

Type Aliases

Type aliases give a meaningful name to a repeated type shape.

The type statement names an annotation shape. Here Scores means a dictionary from user IDs to integer scores.

Source

type UserId = int
type Scores = dict[UserId, int]


def best_user(scores: Scores) -> UserId:
    return max(scores, key=scores.get)

scores: Scores = {1: 98, 2: 91}
print(best_user(scores))

Output

1
dict[str, list[tuple[int, str]]]type Index = …Index
A type alias names a complex annotation once so call sites read as the domain meaning, not the type composition.

Modern aliases are runtime objects that keep their alias name for introspection.

Source

print(UserId.__name__)
print(Scores.__name__)

Output

UserId
Scores

Assignment-style aliases are still common, but they are just ordinary names bound to existing objects.

Source

LegacyName = str
print(LegacyName("Ada"))
print(LegacyName is str)

Output

Ada
True

Notes

See also

Run the complete example

Example code

Expected output

1
UserId
Ada

Execution time appears here after you run the example.