Syntax Grammar
The core syntax follows the pattern of the variable target, a colon, the type expression, and an optional assignment:Basic Implementations
A variable can be annotated at the time of assignment, or it can be declared without an initial value.typing module:
Class and Instance Variables
In object-oriented contexts, variable annotations differentiate between instance variables and class variables. By default, an annotated variable in a class body is treated as an instance variable by static type checkers. To explicitly denote a class attribute, thetyping.ClassVar construct is required.
Runtime Behavior and Storage
Python does not enforce variable annotations at runtime; assigning a string to a variable annotated as an integer will not raise aTypeError. However, Python does evaluate the type expression at runtime for module-level and class-level variables.
For these module-level and class-level variables, the evaluated annotations are stored in a special dictionary accessible via the __annotations__ dunder attribute.
__annotations__ dictionary, and referencing an undefined type in a local annotation (e.g., x: undefined_type = 1) will not raise a NameError.
Forward References and Deferred Evaluation
Because Python evaluates module-level and class-level type expressions at runtime, referencing a type before it is defined raises aNameError. To handle forward references, deferred evaluation can be enabled globally for the module using a __future__ import (PEP 563), or the type can be passed as a string literal.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More





