Python Glossary Русский

Python 3.6+Annotations & typingconstruct

Variable annotation

syntax

Writing x: int = 1 attaches a type hint to a variable or class attribute. The interpreter does not check it; mypy, IDEs and dataclass read it.

Syntax

имя: тип = значение
имя: тип

The main trap: the annotation is not checked at runtime — x: int = "abc" runs without error, and only mypy or an IDE will flag it. The second one: x: int without = assigns nothing, so reading x raises NameError. In a class, an annotation without a value lands in __annotations__ but does not become an attribute — these are exactly the entries @dataclass reads to build its fields.

Examples

x: int = 'abc'
print(x)  # → abc — тип не проверяется
count: int
print(count)  # → NameError
class Point:
    x: int
    y: int = 0
print(Point.__annotations__)  # → {'x': <class 'int'>, 'y': <class 'int'>}
print(hasattr(Point, 'x'), Point.y)  # → False 0

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy