Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Type union X | None and forward-reference annotations

Use `X | None` to allow a value of type `X` or `None`. If a class is defined later, quote the entire annotation or use the `__future__` import.

Version: Python 3.12

Syntax

# Without the future import
class X: ...

value: X | None
value: "X | None"
def make_board(ticket: "Ticket") -> "Board": ...

# Alternative in Python 3.12: copy the next three lines without
# their comment prefixes into a separate module, with the import first.
# from __future__ import annotations
# value: X | None
# def make_board(ticket: Ticket) -> Board: ...

The type union X | None and forward-reference annotations address two different questions: what values are allowed, and when a type name can be looked up. In Python 3.12, X | None means a value of type X or None. Available since Python 3.10, it is equivalent to typing.Optional[X] and typing.Union[X, None], not a call to typing.Union(...). Here | normally constructs a type union, not an integer bitwise OR; a metaclass with its own __or__ can change the result. The hint neither enforces types at runtime nor lets callers omit an argument with no default.

Without the future import, Python 3.12 evaluates ordinary function annotations when the function is defined. If User is not yet defined, User | None raises NameError. Quote the whole union as "User|None"; "User" | None raises TypeError if evaluated immediately. Likewise, "Ticket" and "Board" in a signature refer to classes defined later, not to values of type str.

Alternatively, put from __future__ import annotations near the top of the module and write User | None, Ticket, and Board without quotes in annotations. Python 3.12 then stores the annotations as strings. This import does not defer an ordinary assignment such as Alias = User | None.

Once the classes are defined, typing.get_type_hints() can resolve references stored in __annotations__. The names must be available in the right namespace at that point; supply globalns or localns if needed. A missing name can raise NameError. Evaluating annotations can execute arbitrary code, so do not resolve annotations from untrusted sources.

Examples

from typing import get_type_hints


def make_board(ticket: "Ticket") -> "Board":
    return Board(ticket)


class Ticket:
    def __init__(self, owner: "User|None") -> None:
        self.owner = owner


class Board:
    def __init__(self, ticket: Ticket) -> None:
        self.ticket = ticket


class User:
    pass


print(Ticket.__init__.__annotations__["owner"])
print(get_type_hints(Ticket.__init__)["owner"] == (User | None))
board_hints = get_type_hints(make_board)
print(board_hints["ticket"] is Ticket, board_hints["return"] is Board)
print(make_board(Ticket(None)).ticket.owner is None)

Result

User|None
True
True True
True

The first line shows the raw string `User|None`. The second confirms that the union resolves, the third confirms that both class references resolve, and the fourth shows that the code creates a `Ticket` with `None` as its owner.

Related lessons

  • Python · Lesson 1 · Advanced · Version: 5

Sources