Types are erased

Annotations are checked by nobody and nothing at run time — they are just data in an attribute. Hence a separate validation layer such as pydantic, the dance with TYPE_CHECKING, and the fundamental impossibility of sound static inference.

L1 · 8 minL2 · 10 min📱 phoneverified · CPython 3.11 + pydantic 2.13, linux x86-64

1Predict

Commit to an output and a reason before you open the answer.

Snippet A
def g(x: int = 0):
    return x

print(g("text"))
text
There is an annotation, the value is wrong, there is no error.
Snippet B
def f(x: int, y: "SomeUndefined") -> bool: ...
print(f.__annotations__)
{'x': <class 'int'>, 'y': 'SomeUndefined',
 'return': <class 'bool'>}
A non-existent name in an annotation does not stop the function from existing.
Snippet C
from dataclasses import dataclass

@dataclass
class D:
    a: int

d = D("not a number")
print(repr(d.a))
'not a number'
The dataclass generated __init__ from the annotations and checked nothing.
Snippet D
class C:
    x: int

print(C.__annotations__)
print(hasattr(C, "x"))
{'x': <class 'int'>}
False
The annotation is recorded, the attribute does not exist.

2Mechanism

An annotation is an expression that is evaluated and put into a dictionary. For a function that is __annotations__; for a class and a module, the attribute of the same name.

The interpreter does not use them. No check on a call, on an assignment, anywhere.

Checking is done by a separate tool before running, reading the same source. Validating data at run time is done by a separate library, reading the same annotations as a specification.

Consequence 1 · an annotation affects nothing

Snippets A and C. The function accepts whatever it is given; the dataclass puts whatever it is given into the field. An annotation is metadata lying alongside, and the only one who reads it is whoever you explicitly called.

Hence a practical formulation worth keeping in your head word for word: annotations are documentation — machine-readable, and therefore checkable by an external tool, but documentation all the same. They do not protect against bad data at the program's boundary.

Consequence 2 · a class annotation without a value does not create an attribute

Snippet D. The line x: int in a class body is only an annotation: the name is written into __annotations__, but no assignment takes place, and there is no attribute. The line x: int = 0 does both.

Hence a very common mistake: a field was declared with an annotation, accessed before being assigned in __init__ — and the result is an AttributeError. And hence it is clear how a dataclass works: it reads __annotations__, sees the list of fields and generates an __init__ that would not exist without it.

Consequence 3 · an annotation can refer to something that does not exist

Snippet B. A string in an annotation is not evaluated as a name — it is simply stored. Hence two things that otherwise look arbitrary.

Forward reference: a type declared further down the file is given as a string — def f() -> "Node". The tool will parse it later, when everything is defined.

TYPE_CHECKING: a constant equal to False at runtime and True for the analyzer. An import under it is not executed at startup, and it is the only way to import a type needed only for an annotation without creating a real dependency — and, along the way, to break a circular import from lesson 17.

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from heavy.module import Thing      # not imported at startup

def f(t: "Thing") -> None: ...
Consequence 4 · hence the need for a second layer

Since the runtime checks nothing, and data comes from outside — from a request, a file, a queue — validation has to be performed explicitly. That is how pydantic came about: it reads the same annotations but uses them as a specification for checking and coercion at run time.

It is not an improved dataclass but a different layer, and the difference shows in a measurement: where a dataclass simply lays the arguments out into fields, pydantic checks and coerces the types every time.

200,000 creations of an object with three fieldstime
@dataclass0.032 s
pydantic.BaseModel0.192 s

The sixfold difference is the price of validation, and it should be paid exactly at the boundary. Inside the system, where the data has already been checked, a dataclass is more appropriate.

Consequence 5 · there will be no sound static inference

From lesson 04: an attribute is resolved at runtime, a class can be changed after creation, __getattr__ synthesizes any name. So the analyzer has to assume none of that happened.

So mypy is not “unfinished” — it fundamentally cannot be sound in a language with such a model. Its conclusions are useful and are not proofs, and Any exists as a legitimate exit from the type system. Demanding guarantees from it at the level of the Rust compiler means demanding a different language.

3Limits of the model

Where this stops holding

Some annotations are evaluated after all. By default the expression in an annotation is executed at the moment the function is defined, so a typo in a type gives a NameError on import. The string form and from __future__ import annotations defer evaluation, turning everything into strings.

Annotation-based libraries break because of wrappers. Frameworks that read a signature get it through inspect.signature — and a decorator without functools.wraps replaces it (lesson 08). Hence a non-obvious link: a forgotten wraps breaks type-based validation.

get_type_hints does not always cope. It evaluates string annotations in the module's context, and if a type is visible only under TYPE_CHECKING, the attempt to resolve them at runtime fails with a NameError. This is a deliberate trade: do not pay with an import for the sake of checking.

4Root

Root R8: the language deliberately gave up static guarantees. The annotation syntax appeared in Python 3.0 (PEP 3107) with no semantics at all — simply “a place where you can write anything”. PEP 484 gave it meaning in 2014, and the key decision there is stated outright: checking is not part of the runtime and remains optional.

The reason is practical. Millions of lines of existing code without annotations had to keep working, and typing had to be introduced gradually, file by file. A mandatory check would have made the transition impossible, and any check at runtime — expensive: it would run on every call.

The price is what was taken apart above: no guarantees, a second layer needed for data, an analyzer that cannot be sound. The gain is huge codebases that were typed without being rewritten, and complete freedom to experiment with the type system outside language releases.

5Analogy

Python annotations are comments that a tool can read, and the closest familiar analogue from the C world is header files, if the compiler did not check them and only a linter worked from them. There is a declaration, the contract is described, but there is no enforcement.

The more precise comparison with C++ is this: there a type is what the compiler proved before erasing it, and so there is nothing to check at runtime. In Python a type is what the author declared, and so everything that came from outside has to be checked at runtime. The same word denotes statements of different strength, and all the practice around typing in Python grows out of that difference.

Hence a simple working criterion: an annotation inside the system is a proof you can trust exactly as far as the analyzer is run; an annotation at the system's boundary is a promise that must be checked by code.

6Questions a careful reader asks

Questions that come up on their own if you read closely. The answer is under the question.

If annotations check nothing, why write them?

Because they are checked not by the interpreter but by three other consumers — and all three are real.

The first is a human. The signature def process(data, config, retries) says nothing; def process(data: list[Record], config: Config, retries: int = 3) -> Report answers most of the questions for which you would otherwise have to read the body.

The second is a static analyzer. mypy finds a whole class of errors before running: a None that turned up where it was not expected; mixed-up arguments of the same type; a forgotten branch in a match. Not all errors — but the ones it finds, it finds for free and across the whole codebase at once.

The third is runtime libraries. And this is the most underrated: an annotation is data in a dictionary, and someone reads it.

from dataclasses import dataclass

@dataclass
class P:
    x: int
    y: int = 0

print(P.__annotations__)          # → {'x': <class 'int'>, 'y': <class 'int'>}
print(P(1, 2))                    # → P(x=1, y=2)

dataclass does not check types — it reads __annotations__ to learn the list and order of the fields, and generates __init__, __repr__ and __eq__. pydantic, attrs, FastAPI, SQLAlchemy 2.0 and typing.NamedTuple stand on the same mechanism.

That is, without annotations half of the modern Python stack simply does not work — not because types are checked, but because they declare structure.

Why does mypy let bugs through — can that be fixed?

It cannot, and this is not a shortcoming of mypy but a consequence of R2.

A sound analyzer must guarantee: if the check passed, there will be no type error at execution. For that, an object's type must not be changeable after the check. In Python it can be:

class A:
    def hello(self): return "A"

def use(a: A) -> str:
    return a.hello()          # mypy: all fine

class B:
    def hello(self): return 1   # not str!

a = A()
a.__class__ = B                 # the object's type changed on the fly
print(use(a))                   # → 1, while str was promised

Add setattr with a computed name, __getattr__, metaclasses, exec, and C extensions that can substitute anything in an object — and it becomes clear there is nothing to prove.

That is why all Python analyzers are deliberately unsound: they find most real errors and stay silent about the rest. This is an engineering compromise, not a temporary state. Any in the type system is not a stub but an honest “there is no proof here”.

What follows in practice. Types are useful but do not replace tests. Data that came from outside — from HTTP, a database, a file — must be validated at runtime: there an annotation says nothing at all. And disallow_untyped_defs on new modules gives more than an attempt to scrub Any out of old ones.

pydantic costs six times as much — when is it justified?

At the process boundary — almost always. Inside — almost never.

The measurement from this lesson: creating an object through pydantic is about six times more expensive than through a dataclass. The difference is the price of validation: type checks, coercion, parsing nested structures, assembling error messages.

from dataclasses import dataclass
from pydantic import BaseModel

@dataclass
class D:
    x: int

class P(BaseModel):
    x: int

D(x="not a number")      # → created, the field stays a string
P(x="not a number")      # → ValidationError

Where it is worth paying. Data came from outside and is unchecked: the body of an HTTP request, someone else's API response, a config, a line from a queue, the contents of a file. Here an annotation gives nothing, and validation is the only thing standing between someone else's data and your code. A sixfold difference on an object created once per request is not measurable against the network.

Where it is not. Internal structures created by your own code and already checked at the entrance: tree nodes, intermediate records, points. Here there is nothing to validate — the data did not come from outside — and there are millions of objects. dataclass(slots=True) or NamedTuple.

The rule in one phrase: validate once, at the boundary, and carry checked types from there on. Validation in the middle is distrust of your own code, paid for six times over.

TYPE_CHECKING — why such a crutch?

It resolves a conflict between two truths: the type needs an import, and the runtime does not.

The situation is typical: module a annotates a function with a class from module b, and b imports a. An import for the sake of an annotation creates a cycle — even though at runtime it is not needed at all, since the annotation is not evaluated anyway.

from __future__ import annotations      # annotations become strings
from typing import TYPE_CHECKING

if TYPE_CHECKING:                       # False at execution, True for mypy
    from heavy_module import Thing

def use(t: Thing) -> None: ...          # mypy sees the type, the runtime does not import it

TYPE_CHECKING is an ordinary constant equal to False; analyzers treat it as True by convention. No magic.

Two gains. Breaking the import cycle — and startup time: heavy modules needed only for annotations are not loaded at all. Lesson 22 shows that import numpy costs 88 ms; if it is needed only for a type in a signature, there is no reason to pay.

The price. Everything that reads annotations at runtime — get_type_hints, pydantic, FastAPI — will not find the name and will fail. So you must not do this for pydantic models, but you can for ordinary functions.

The crutch is acknowledged: PEP 649 (3.14) changes the model to lazy, on-demand evaluation of annotations, which removes both the need for from __future__ import annotations and most cases of TYPE_CHECKING. But the old way will live on for a long time — R9.

Bottom line. An annotation is an expression that is evaluated and put into the __annotations__ dictionary; the interpreter never uses it. Hence: a function accepts whatever it is given, a dataclass puts whatever it is given into a field, and x: int in a class body records an annotation but does not create an attribute. Since an annotation executes nothing, it can mention something that does not exist yet — that is how forward references work, and TYPE_CHECKING, which is False at runtime and lets you import a type without creating a dependency. And since the runtime does not check, data from the boundary needs a separate layer: pydantic reads the same annotations as a specification and pays for it with a sixfold difference in object creation time. And sound static inference is fundamentally impossible in this language — an attribute is resolved at runtime, a class is mutable, __getattr__ synthesizes anything, so the analyzer's conclusions are useful but are not proofs.
From here on — optional
counterfactualC++, TypeScript and RustErased types versus checked ones — and a natural experiment run twice

TypeScript is the cleanest natural experiment: the same gradual types, the same erasure at compilation, the same result. Data from the boundary has to be validated by a separate library (zod there, pydantic here), and that is not a coincidence of taste but a consequence of an identical decision. Two independent languages, one conclusion.

C++ is the opposite pole: types exist only at compile time and are fully checked there, while at runtime almost nothing of them remains except RTTI. That is, there is erasure here too — but after the check, not instead of it. That is exactly the difference: C++ erases what it has already proved, Python erases what nobody checked.

Rust goes further: the type system proves not only “this is an integer” but also lifetimes and ownership, and without the proof the program does not build. The price is a model you have to keep in your head, and the impossibility of gradual adoption.

Three points on one axis: proved and erased, declared and erased, proved together with ownership.

🐛 bugThe validation that is not thereA dataclass with annotations looks like a contract, while the data comes in from outside unchecked

Parsing an external API's response. The types are declared; the error surfaces three layers down.

@dataclass
class Order:
    id: int
    amount: float
    created: datetime

def parse(payload: dict) -> Order:
    return Order(**payload)          # ← nothing has been checked

order = parse(response.json())
total += order.amount                # amount turned out to be the string "12.50"

The external service sent a number as a string — an ordinary thing. The dataclass accepted it: it generates __init__ from the list of fields and does not look at the types (consequence 1). The failure will happen later, in arithmetic, and the traceback will point at a line where the data has long been wrong.

Worse is when it does not fail: created stays a string, date comparison starts working lexicographically, and the error becomes silent.

Review lets it through because the annotations look like a check. That is the most insidious part: the code reads as typed.

class Order(BaseModel):
    id: int
    amount: float
    created: datetime

order = Order.model_validate(response.json())
# "12.50" -> 12.5, an ISO string -> datetime, garbage -> ValidationError here

The rule derived from consequence 4: validation at the system's boundary, dataclasses inside. The boundary is everything that did not come from your own code: HTTP, a queue, a file, environment variables, a raw database response. Inside, where the data has already been checked, there is no reason to pay a sixfold price for every object.

⚡ techniqueTypes where they pay offIntroduce them not wholesale but along module boundaries — and switch on strictness only for new code first

Typing a large codebase pays off unevenly, and the order of introduction matters more than completeness.

Where it pays off at once: the signatures of a module's public functions, data models, boundaries between subsystems. There an annotation replaces reading the implementation and catches real errors during refactoring.

Where it barely pays off: local variables (inference works anyway), short internal functions, tests. There an annotation is noise that bloats diffs.

How to switch it on in a live project. Not “go through everything”, but put the check into CI at once — strict, though, only for new code:

# pyproject.toml
[tool.mypy]
python_version = "3.11"
ignore_missing_imports = true

# strict — only where typing is already done
[[tool.mypy.overrides]]
module = ["myapp.core.*", "myapp.api.*"]
disallow_untyped_defs = true
strict_equality = true

The list of modules in overrides grows as they become ready — this is the very gradualness for which the language gave up mandatory checking (see “Root”). The reverse path, when strictness is switched on globally and a thousand exceptions are added, usually ends with the exceptions never being removed.

What gives the most per line: disallow_untyped_defs on new modules and a ban on implicit Any at the boundaries. Protocol from lesson 11 — where you describe an expectation of someone else's class: it requires no inheritance and creates no dependency.

💻 terminalCheck it in the REPLFour snippets plus a NameError in an annotation, from __future__ and get_type_hints

Run the snippets and check them against your prediction. Then the first batch, which pastes in whole:

def f(x: Undefined) -> None: ...
# A NameError at definition? And if you write x: "Undefined"?

from typing import get_type_hints
class Node:
    parent: "Node"
print(get_type_hints(Node))
# How did the string turn back into a class?

import typing
print(typing.get_type_hints(len))
# Why is it empty for a built-in function?

The second — necessarily in a new file or a fresh kernel: from __future__ has to be the first line, otherwise SyntaxError. That in itself is part of the answer to why PEP 563 did not become the default.

from __future__ import annotations

def g(x: Undefined) -> None: ...
print(g.__annotations__)
# What changed, and what did the annotations turn into?

The second question matters in practice: deferred evaluation of annotations removes the NameError and the cost of imports, but breaks everything that tries to read types at runtime without get_type_hints.

sourcedataclasses and typingWhere the standard library reads annotations as data

Lib/dataclasses.py. We come back here a third time, and now through the main entrance: _process_class reads __annotations__, builds the list of fields and generates __init__ as text through exec. Notice that a field's type is used only as a sign “this is a field” — it is never compared with anything. Consequence 1 in the source of the standard library.

Lib/typing.py, the get_type_hints function. Here you can see how string annotations turn back into objects: they are evaluated through eval in the module's namespace. Hence the limitation from “Limits of the model” — if a name is available only under TYPE_CHECKING, there is nothing to evaluate.

Lib/functools.py, singledispatch. A rare case where the standard library uses an annotation as working information: the type of the first argument determines which implementation will be called. A type-dispatch mechanism built on top of metadata.

L2Where annotations live and what they cost__annotations__, deferred evaluation and the cost of importing typing

From L1 you know that an annotation is data. Here: exactly where, and what it costs.

For a function it is the __annotations__ dictionary, filled when the function object is created. For a class and a module, the attribute of the same name, assembled by the compiler from the lines with a colon. The key detail: by default the expressions are evaluated at the moment of definition.

from typing import List, Dict
def f(x: List[Dict[str, int]]) -> None: ...
print(f.__annotations__)
# → {'x': typing.List[typing.Dict[str, int]], 'return': None}

That is, importing a module creates real objects of generic types. In a large project with thousands of signatures this is a noticeable part of startup time — and one of the reasons from __future__ import annotations appeared: with it, annotations stay strings and are not evaluated at all.

from __future__ import annotations
def g(x: List[Dict[str, int]]) -> None: ...
print(g.__annotations__)
# → {'x': 'List[Dict[str, int]]', 'return': 'None'}

The trade is explicit: a faster import and no NameErrors in annotations — but everything that reads types at runtime must call get_type_hints, and that may not cope.

About the price of validation. The sixfold difference from consequence 4 is pydantic 2, whose core is compiled in Rust. With the first version, entirely in Python, the gap was several times larger. A useful rule of thumb when choosing: validating a thousand objects per request is noticeable, a dozen is not.

L3Where this is in the sources and standardscompile.c, typing.py, PEP 484 and 563

Tag v3.11.15.

  • Python/compile.c — compiling annotations: you can see that for a function a dictionary is built, while for variables in a class there is an entry in __annotations__ without an assignment (consequence 2).
  • Lib/typing.py — the whole type system in Python: generics, Protocol, get_type_hints. Nothing in C.
  • PEP 484 — the decision that checking is not part of the runtime; read the “Non-goals” section.
  • PEP 563 — deferred evaluation of annotations, and the story of why it never became the default behaviour.
connectionsWhere this leadsL04, L08, L11, L17 · the contrast with TypeScript, C++ and Rust
root R8 · Giving up static guarantees
← foundation L04 · obj.x, end to end — why static inference cannot be sound
← foundation L08 · Functions and decorators — a forgotten wraps breaks signature-based validation
← foundation L17 · Import, end to end — TYPE_CHECKING as a way to break an import cycle
↔ contrast TypeScript: the same decision, the same result — an independent confirmation
↔ contrast C++ erases what was proved, Python erases what was declared
↔ contrast L11 · Protocols — structural typing versus nominal within the type system itself
readingFurther readingPEP 484 🟥 · typing 🟧 · PEP 563 🟦

Written by · The Python Canon