Python Glossary Русский

Python 3.9+Annotations & typingterm

int / str / list / dict (annotations)

built-in

Since Python 3.9 the built-in types are used as generics directly: list[int], dict[str, int]. Earlier this required typing.List and typing.Dict.

Syntax

x: int = 5
s: str = 'hi'
items: list[int] = [1, 2, 3]
mapping: dict[str, int] = {'a': 1}

Annotations are not checked at runtime: a function declared to take list[int] will accept a list of strings without a murmur — only mypy or a similar checker will spot the mismatch. One type applies to the whole container, so heterogeneous data calls for a union or a tuple with per-position types. typing.List and typing.Dict have been deprecated since 3.9 and remain only for compatibility with older code.

Examples

def greet(name: str) -> str:
    return f'Hello, {name}!'
print(greet('Alice'))  # → Hello, Alice!
def total(nums: list[int]) -> int:
    return sum(nums)
print(total([1, 2, 3]))  # → 6
coords: tuple[float, float] = (1.0, 2.0)  # → аннотация кортежа
matrix: list[list[int]] = [[1, 2], [3, 4]]  # → вложенные типы

See also

Open in the full glossarydocs.python.orgReport an inaccuracy