> ## 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.

# Python Variable Annotation

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:

```text theme={"dark"}
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.

```python theme={"dark"}

# 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:

```python theme={"dark"}
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.

```python theme={"dark"}
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.

```python theme={"dark"}
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.

```python theme={"dark"}

# 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 
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Python Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
