Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Quoted forward-reference annotations

An annotation such as "Node" describes a type using a name stored as text, even when the class is defined later. Python 3.14 defers annotation evaluation by default, so quotes are often no longer necessary, but remain valid syntax.

Version: Python 3.14; repository image, production runtime not attested

Syntax

def f(value: "LaterType") -> "LaterType": ...

Quoted forward-reference annotations use a string literal as a type hint, such as node: "Node" or -> "Node". They can refer to a class defined later, including a class referring to itself. They do not mean that the expected value has type str.

In Python 3.14, annotation evaluation is deferred by default, so an unquoted Node usually also suffices for this kind of reference. Explicit "Node" remains valid. This is distinct from from __future__ import annotations, which causes annotations to be stored as strings. Type hints alone do not enforce argument types at runtime.

typing.get_type_hints() resolves string references into actual types. Call it only when the required names are available in the appropriate namespaces; an unresolved name can cause NameError. The function may execute code contained in annotations, so do not use it on untrusted annotations.

In the example, identity appears before the definition of Node, but the hints are inspected afterward. The two True results demonstrate the expected resolution of both annotations to the class Node, and the final line shows the class name of the returned object.

Examples

from typing import get_type_hints


def identity(node: "Node") -> "Node":
    return node


class Node:
    pass


hints = get_type_hints(identity)
print(hints["node"] is Node)
print(hints["return"] is Node)
print(identity(Node()).__class__.__name__)

Result

True
True
Node

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources