Skip to main content
Variable annotation is a syntactic feature introduced in Python 3.6 (PEP 526) that allows developers to attach type metadata directly to variables. It extends the type hinting system beyond function signatures, providing a standardized way to declare the expected type of a variable for static type checkers, linters, and IDEs, without altering Python’s underlying dynamic typing semantics at runtime.

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.
When using complex types, annotations leverage built-in generic types (Python 3.9+) or the 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, the typing.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 a TypeError. 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.
Scope Exception: Annotations applied to local variables inside functions are not evaluated at runtime. According to PEP 526, this design choice prevents performance overhead. Consequently, local annotations are not stored in any __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 a NameError. 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