Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Annotated Variables: Syntax and Practical Use

Learn how to annotate variables in Python, how annotations differ from type hints, and how static type checkers use them.

~5 min readPython
#type hints#variable annotations#PEP 526#static typing
Illustration of Python variable annotation syntax showing a variable name, colon, and type.

When you assign a value to a variable in Python, the interpreter does not enforce a fixed type for the name. x = 5 and x = "text" can both appear in the same scope. Variable annotations, introduced in Python 3.6 via PEP 526, let you declare the intended type of a variable without changing how the assignment behaves at runtime. Understanding the exact semantics matters because annotations affect how you document intent, how static type checkers interpret your code, and how you debug type-related issues.

What a Variable Annotation Actually Does

A variable annotation attaches a type to a name at the point of assignment. It does not enforce the type at runtime. At module and class level, the annotation is stored in the __annotations__ dictionary, but the assignment itself is unchanged. For example:

python
count: int = 0

This tells readers and tools that count is expected to be an integer. The runtime behavior is identical to count = 0. The annotation is metadata, not a runtime constraint.

Syntax for Annotating Variables

The basic syntax is name: type = value. The type can be any valid expression, including built-in types, custom classes, typing constructs, or string literals for forward references. You can annotate a variable without an assignment at module or class scope:

python
items: list[str]

This creates an entry in the module or class __annotations__ with the value list[str]. The variable itself is not defined until you assign to it, so you must still assign a value before using the variable. Inside a function, a local annotation is not stored in __annotations__; it is effectively documentation for type checkers and readers.

Annotated assignments follow the normal assignment syntax, one statement per variable:

python
x: int = 1 y: str = "hello"

Each statement annotates the target name. Parentheses are not required, but they can help readability in some contexts.

Annotations vs. Type Hints: What's the Difference?

The terms are often used interchangeably. A type hint is any annotation on a function parameter, return value, or variable that provides type information. A variable annotation is the specific syntax for declaring the intended type of a variable, as opposed to annotating a function signature. In practice, both are processed by the same machinery and are used by static type checkers. The distinction is useful when reading code: a variable annotation declares the intended type of a name in the current scope, while a function parameter annotation describes part of a callable's contract.

How Annotations Behave at Runtime

At runtime, module-level and class-level annotations are stored in the __annotations__ attribute. Local variables inside a function are not stored at all. Consider this module:

python
# module.py x: int = 5

After importing the module, module.__annotations__ contains {'x': int}. If you annotate a class attribute:

python
class Point: x: int y: int

Then Point.__annotations__ will have the entries. However, for variables inside a function:

python
def f(): a: int = 1 print(a)

There is no __annotations__ entry for the local variable. The annotation is ignored at runtime. This matters because function-local annotations cannot be used for runtime reflection.

Using Annotations with Static Type Checkers

The primary benefit of variable annotations is that static type checkers like mypy, pyright, and pyre can read them and catch type mismatches before the code runs. For example:

python
def process(data: list[int]) -> int: total: int = 0 for item in data: total += item return total

If you later assign a string to total, a type checker will report an error. The annotation turns an implicit assumption into an explicit contract that can be verified automatically.

To use the annotation, configure your project's type checker and run it on the module. With mypy, mypy my_module.py reports inconsistencies. The checker uses the annotation to infer the expected type and validates assignments and usage against it.

Common Mistakes and How to Avoid Them

One common mistake is confusing annotations with type conversion. Writing x: int = "5" does not convert the string to an integer; it annotates the variable as an integer while assigning a string. The runtime value remains a string. Type checkers will flag this as an error, but the code will run without raising an exception.

Another mistake is repeating a complex type in many annotations when a type alias would be clearer. If you find yourself writing dict[str, list[tuple[int, str]]] repeatedly, define an alias:

python
from typing import TypeAlias DataMap: TypeAlias = dict[str, list[tuple[int, str]]]

Then use DataMap in your annotations. This improves readability and makes future changes easier.

A third issue is relying on annotations for runtime validation. Since annotations are not enforced, they cannot replace runtime checks. If you need to validate data at runtime, use a library like Pydantic or write explicit validation logic.

When to Use Annotated Variables (and When Not To)

Use variable annotations when building a codebase that will be checked by a static type checker, especially if multiple developers work on the same code. Annotations make intended data shapes explicit and catch a class of bugs early. They are also useful in public APIs where expected types are part of the contract.

Avoid annotations in small scripts or prototypes where the cost of maintaining them outweighs their benefit. If a variable's type is obvious from initialization and the code is never checked, an annotation can add noise. Similarly, do not annotate every local variable when the type is clear from context. Use annotations at the boundaries of your code: function signatures, class attributes, and module-level constants. Local variables often do not need explicit annotations because the checker can infer them from the assignment.

Compatibility and Future Considerations

Variable annotations are available in Python 3.6 and later. If you support Python 3.5 or earlier, you cannot use this syntax. For code that must run on older versions, type comments (# type: int) are an alternative, though they are less readable and less common in modern tooling. If you use from __future__ import annotations (Python 3.7+), module-level and class-level annotations are stored as strings, which can postpone evaluation and help with forward references. This is particularly useful when a type is defined later in the module.

Annotations are not only for type checkers. Other tools, such as dataclasses (which inspect __annotations__ to generate fields) and serialization libraries, also rely on them. Understanding runtime behavior helps avoid breaking those tools by relying on annotations that are not present.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.