Sub topic 15
Forward References and Postponed Evaluation
This chapter assumes you can annotate functions and classes, read X | None unions, and know that the interpreter stores hints without enforcing them. It covers how to refer to a type that doesn't exist yet when Python reads the annotation.
The problem: names must exist when the annotation runs
Before Python 3.14, an annotation on a function or variable is an ordinary expression. Python evaluates it when it executes the def statement, which happens while the class body is still being built. Inside a class, the class's own name is not bound yet, so this fails:
class Node:
def __init__(self, value: int, next: Node | None = None) -> None:
self.value = value
self.next = nextRunning this on Python 3.13 or earlier raises NameError: name 'Node' is not defined. A type used before its definition is called a forward reference. The same error appears when two classes refer to each other and the second is defined further down the file.
Fix 1: quote the annotation
Wrap the type in quotes. Python stores the string and never evaluates it at definition time. A static checker parses the string as if it were code.
from typing import get_type_hints
class Node:
def __init__(self, value: int, next: "Node | None" = None) -> None:
self.value = value
self.next = next
print(Node.__init__.__annotations__["next"])
print(get_type_hints(Node.__init__)["next"])The first line prints the raw string Node | None. The second prints a real union of Node and None, because get_type_hints looks the names up and evaluates the text.
Quote only the part that needs it. list["Node"] is valid and keeps the rest evaluated normally. "Node" | None fails at runtime, because a plain string does not support |. Quote the whole union, as above.
Fix 2: postpone every annotation in the module
Putting from __future__ import annotations at the top of a module turns every annotation in it into a string automatically. You then write natural, unquoted code:
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass
class Category:
name: str
parent: Category | None = None
children: list[Category] = field(default_factory=list)
root = Category("root")
child = Category("child", parent=root)
root.children.append(child)
print(Category.__annotations__)The output shows every value as text: {'name': 'str', 'parent': 'Category | None', 'children': 'list[Category]'}. The @dataclass decorator works fine with strings, because it only needs the field names and a check for ClassVar.
The future import must be the first statement after the module docstring and comments. It applies only to annotations. An ordinary assignment such as Pair = tuple[Node, Node] is still evaluated immediately and still needs Node to exist.
Reading postponed annotations at runtime
Once annotations are strings, code that wants real types has to convert them. Use typing.get_type_hints(obj), not obj.__annotations__. It evaluates each string in the module's global namespace (and the class namespace for classes) and returns actual type objects.
get_type_hints fails with NameError when a name is not resolvable at that moment, for example a function-local class or a name imported only under TYPE_CHECKING. Libraries that read hints at runtime, such as validation and serialization frameworks, call it internally and run into this.
Fix 3: imports needed only for type checking
Circular imports are the second source of forward references. If customer.py imports billing.py just to name a type, and billing.py imports customer.py, the program may fail at import time. The constant typing.TYPE_CHECKING is False at runtime and treated as True by checkers, so the import runs only for the checker:
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from billing import Invoice
class Customer:
def __init__(self, name: str) -> None:
self.name = name
self.invoices: list[Invoice] = []
def add(self, invoice: Invoice) -> None:
self.invoices.append(invoice)
print(Customer("Ada").invoices)This runs even though no billing module exists, because the annotations are never evaluated. A checker with billing.py available verifies the types. Without the future import, you would have to quote every use: "Invoice".
The cost is that get_type_hints(Customer.add) raises NameError, since Invoice was never imported at runtime. Import under TYPE_CHECKING only the names you do not need at runtime.
Python 3.14 and deferred evaluation
Python 3.14 changed the default. Annotations are no longer evaluated when the def or class body runs. They are evaluated lazily, on first access of __annotations__ or through the annotationlib module. In 3.14 the unquoted Node example at the top of this chapter works without any import. The from __future__ import annotations line is still accepted, but it keeps the older string behavior, so code that must run on several versions often keeps it.
Choosing an approach
| Approach | Works on | Stored in `__annotations__` | Main limitation | Column |
|---|---|---|---|---|
| Quoted annotation | All versions | Text for that annotation only | Easy to forget; `"A" \ | None` must be quoted as a whole |
| `from __future__ import annotations` | 3.7 and later | Text for every annotation in the module | Runtime readers must use `get_type_hints` | |
| `if TYPE_CHECKING:` import | All versions | Unchanged | Names unavailable to `get_type_hints` | |
| Default behavior of Python 3.14 | 3.14 and later | Evaluated on first access | Not available on older versions |
Common errors
- Quoting an alias but not its use. After
Tree = "Node | None", the alias is just a string. A checker understands it, but runtime code may not. - Using
|in a runtime expression on old versions. The future import makesint | Nonesafe in annotations on Python 3.7 to 3.9. It does not help inisinstance(x, int | None)or in alias assignments, which need 3.10 or later. - Expecting types in
__annotations__. With the future import,Category.__annotations__["parent"]is the string'Category | None', so comparing it with a class always fails. - Using the class name for a return type that may be subclassed.
def clone(self) -> "Node"makes subclasses returnNodein the checker's view. On 3.11 and later,typing.Selfexpresses "same class as the receiver" more accurately.
Exercise
On Python 3.12, a class Widget has the method def clone(self) -> Widget: and raises NameError when the module is imported. Give two different fixes and name one drawback of the module-wide fix.
Show answer
Fix 1: quote the annotation, def clone(self) -> "Widget":. Fix 2: add from __future__ import annotations as the first statement of the module, which stores every annotation as text. The drawback of the module-wide fix is that __annotations__ then holds strings, so code that needs real type objects must call typing.get_type_hints, which can itself fail with NameError for names that exist only under TYPE_CHECKING.
Exercise
A module imports Invoice inside if TYPE_CHECKING: and uses it in an annotation with the future import active. Why does the module import without error, and what happens when get_type_hints is called on a function that uses Invoice?
Show answer
The module imports cleanly because annotations are stored as strings and never evaluated, and the guarded import never runs because TYPE_CHECKING is False at runtime. get_type_hints tries to evaluate the string "Invoice", finds no such name in the module's globals, and raises NameError.