Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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:
target: type_expression [= initial_value]

Basic Implementations

A variable can be annotated at the time of assignment, or it can be declared without an initial value.

# Annotated assignment
max_connections: int = 100
is_active: bool = True


# Uninitialized annotation (declaration only)
user_id: str
When using complex types, annotations leverage built-in generic types (Python 3.9+) or the typing module:
from typing import Union, Optional, Any


# Generic collections
endpoints: list[str] = ["/api/v1/users", "/api/v1/status"]
payload: dict[str, Any] = {"id": 123, "data": None}


# Union and Optional types
timeout: Union[int, float] = 5.5
token: Optional[str] = None

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.
from typing import ClassVar

class ServerConfig:
    # Class variable: shared across all instances
    default_port: ClassVar[int] = 8080
    
    # Instance variable declaration
    host: str
    
    def __init__(self, host: str):
        self.host = host

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.
class Point:
    x: float
    y: float = 0.0

print(Point.__annotations__)

# Output: {'x': <class 'float'>, 'y': <class 'float'>}
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.

# Deferred evaluation (must be at the very top of the file)
from __future__ import annotations


# String literal forward reference (legacy approach)
node: 'Node'

class Tree:
    # Valid even though Tree is not fully defined yet
    left_child: Tree 
Master Python with Deep Grasping Methodology!Learn More