CKTIS / Python
Forward-reference annotation
In Python 3.12, a quoted type annotation can refer to a name that becomes available only after the function is defined.
Version: Python 3.12
Syntax
def run_test(test: "Callable[[], None]") -> None:
test()In Python 3.12, without from __future__ import annotations, function annotations are evaluated when the def statement runs, not when the function is called. An unquoted name that is not yet available can cause NameError at that point. A forward-reference annotation can use a string literal such as "Callable[[], None]" so the type expression can be resolved later.
In the run_test signature, Callable[[], None] describes a callable that accepts zero arguments ([]) and returns None. The separate -> None describes what run_test itself returns. The quotes do not mean you should pass a string, and Python does not automatically check the argument against the annotation.
run_test.__annotations__["test"] holds the string. typing.get_type_hints(run_test) evaluates the expression in the appropriate namespace and can raise NameError if Callable is still missing. If Callable is already available when def runs, the quotes are unnecessary. Do not resolve untrusted annotations: evaluating the expressions they contain can execute code.
Examples
from typing import get_type_hints
def run_test(test: "Callable[[], None]") -> None:
test()
from collections.abc import Callable # Deliberately imported after run_test.
def smoke_test() -> None:
print("Test ran", end="")
print(repr(run_test.__annotations__["test"]))
print(get_type_hints(run_test)["test"] == Callable[[], None])
run_test(smoke_test)Result
'Callable[[], None]' True Test ran
The import from `collections.abc` deliberately comes after `run_test` is defined. The first line shows the string’s representation, `True` confirms that the resolved hint matches the expected type, and `Test ran` comes from the callback.
Related lessons
- Python · Lesson 26 · Basic · Version: 3