Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Forward references in type annotations

In Python 3.12, quote a type name that is not yet available when a method is defined, then resolve the reference later if you need the class object.

Version: Python 3.12

Syntax

# Quote a name that is not bound yet:
def f(value: "Later") -> "Later": ...

# For a union, quote the entire expression:
def g(value: "int | Later") -> None: ...

# Alternatively, as a separate module using postponed evaluation:
from __future__ import annotations

def f(value: Later) -> Later: ...

Use forward-reference type annotations when a function signature refers to a type whose name is not yet available at the definition site. In Python 3.12, without postponed evaluation, function annotations are evaluated when def runs, not when the function is called. A bare type name that is not available then raises NameError. Annotations help static type checkers; Python itself does not use them to validate arguments or return values.

In WorkItem.from_dict, -> "WorkItem" refers to the class whose body is still executing. In Project.add_module, module: "Module" refers to a class defined further down. In each case the string literal records the reference without looking up the name immediately. For a union, quote the entire expression: "int | Module". Without postponement, int | "Module" raises TypeError because | receives a type and a string.

Alternatively, put from __future__ import annotations at the top of the module, after its docstring if it has one. In Python 3.12 this import stores function annotations as strings, so you can write -> WorkItem and module: Module without quotes. It does not postpone ordinary expressions outside annotations, such as parameter defaults.

In the example, __annotations__ contains strings. Once both classes are defined, typing.get_type_hints() looks up the names in the relevant namespaces and resolves the references to class objects. A missing name can still cause NameError, for example if it was imported only inside if TYPE_CHECKING:. Do not resolve untrusted annotations: evaluating annotation expressions can execute code.

Examples

from typing import get_type_hints


class WorkItem:
    def __init__(self, title: str) -> None:
        self.title = title

    @classmethod
    def from_dict(cls, data: dict[str, str]) -> "WorkItem":
        return cls(data["title"])


class Project:
    def __init__(self) -> None:
        self.modules = []

    def add_module(self, module: "Module") -> None:
        self.modules.append(module)


class Module:
    pass


print(repr(WorkItem.from_dict.__annotations__["return"]))
print(repr(Project.add_module.__annotations__["module"]))
print(get_type_hints(WorkItem.from_dict)["return"] is WorkItem)
print(get_type_hints(Project.add_module)["module"] is Module)

Result

'WorkItem'
'Module'
True
True

The first two lines show the string representations from `__annotations__`. The two `True` results show that the resolved annotations are the exact `WorkItem` and `Module` class objects.

Related lessons

  • Python · Lesson 3 · Advanced · Version: 5
  • Python · Lesson 7 · Advanced · Version: 5

Sources