Skip to content

Module 17 · Advanced Python Concepts — topic 12 of 14

Annotations

The annotation mechanism behind type hints: function and variable annotations, where they are stored, annotations without values, arbitrary annotation expressions, and using annotations at runtime for validation and dataclasses.

Beginner 8 min read·Lesson 258 of 306 in Python Programming

Learning objectives

  • Write function and variable annotations
  • Read annotations at runtime
  • Use annotations to drive behaviour such as validation

Definition

Annotations are expressions attached to function parameters, return values and variables using : and ->. Python stores them in __annotations__ without interpreting them, so they can hold type hints or any other metadata.

Introduction

Type hints are the most common use of annotations, but annotations themselves are simply metadata. Libraries read them to generate code, validate data and build APIs.

Why it matters

Understanding annotations explains how dataclasses, pydantic and FastAPI know which fields and types you declared.

Detailed explanation

Function annotations: def f(x: int) -> str. They are stored in f.__annotations__ as a dictionary, with the return type under 'return'.

Variable annotations: count: int = 0. In a class body, annotations declare fields; dataclasses use them to generate __init__.

An annotation without a value (retries: int) declares a name but does not create the attribute.

Annotations can be any expression, such as strings describing units, though type checkers expect types.

typing.get_type_hints (or annotationlib in Python 3.14) is the recommended way to read evaluated annotations, resolving forward references.

Python 3.14 evaluates annotations lazily, only when they are requested, which speeds up imports and allows referring to classes defined later.

Decorators can read a function's annotations to check argument types, convert values or generate documentation.

Syntax

Python
class Config:
debug: bool = False
retries: int # declared, no value
def area(r: float) -> float:
return 3.14 * r * r
print(area.__annotations__)
  • Stored, not enforced.
  • Class annotations declare fields.
  • Read them with get_type_hints.

Code examples

Class annotations

Python
class Config:
debug: bool = False
retries: int
print(Config.__annotations__)
print(hasattr(Config, "debug"), hasattr(Config, "retries"))
Output
{'debug': <class 'bool'>, 'retries': <class 'int'>}
True False

Annotations are just metadata

Python
def area(r: "radius in cm") -> "square cm":
return 3.14 * r * r
print(area(2), area.__annotations__)
Output
12.56 {'r': 'radius in cm', 'return': 'square cm'}

More examples

Validation driven by annotations

Python
import functools
import typing
from dataclasses import dataclass, fields
def validate(func):
hints = typing.get_type_hints(func)
@functools.wraps(func)
def wrapper(*args):
for (name, expected), value in zip(hints.items(), args):
if not isinstance(value, expected):
raise TypeError(f"{name} must be {expected.__name__}, got {type(value).__name__}")
return func(*args)
return wrapper
@validate
def repeat(text: str, times: int) -> str:
return text * times
print(repeat("ab", 3))
try:
repeat("ab", "3")
except TypeError as e:
print(e)
@dataclass
class Item:
name: str
price: float = 0.0
print([(f.name, f.type.__name__) for f in fields(Item)])
Output
ababab
times must be int, got str
[('name', 'str'), ('price', 'float')]

Step-by-step explanation

  • The decorator reads the parameter annotations once, when the function is decorated.
  • Each positional argument is checked against its annotated type before the function runs.
  • dataclasses read the class annotations to discover the fields name and price.

Expected output

Running “Validation driven by annotations” prints exactly:

TextOutput
ababab
times must be int, got str
[('name', 'str'), ('price', 'float')]

Practical applications

  • pydantic models validating JSON input.
  • FastAPI turning annotated parameters into query parameters and request bodies.

Best practices

  • Use annotations mainly for types.
  • Read them with get_type_hints.
  • Keep runtime validation explicit and tested.

Common mistakes

Expecting an annotation to create an attribute

Avoid

class C:
x: int
C().x # AttributeError

Prefer

class C:
x: int = 0

An annotation without a value only declares the name.

Important notes

  • typing.Annotated[int, 'metadata'] combines a type with extra metadata for libraries.

Key takeaways

  • Annotations attach metadata to parameters, returns and variables.
  • They are stored in __annotations__ and not enforced.
  • Libraries read them to generate behaviour.

Try it yourself

  1. 1
    Extend the validate decorator to support keyword arguments.
  2. 2
    Print the annotations of every method in a class you wrote earlier.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

16 questions cover the “Advanced Python Concepts” module. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
  • AdvancedWhat is printed?
  • AdvancedWhat is printed?
Practise this module