Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Type unions: X | Y and X | None

In type annotations, the union X | Y means a value of type X or Y, while the union X | None also permits None. Annotations describe allowed values but do not automatically enforce runtime checks.

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

Syntax

X | Y
X | None

Under the standard behavior of |, X | Y creates a type union equivalent to typing.Union[X, Y]: a value can be of type X or Y. At runtime, however, a custom metaclass can override __or__. Even if both operands are types, X | Y can then return something other than a union, in which case it is not equivalent to typing.Union[X, Y]. More types can be combined, such as int | str | None. Here, | combines types rather than Boolean values. The syntax is available from Python 3.10; in Python 3.14, union objects are instances of typing.Union, and types.UnionType is an alias for that class.

As a type union, X | None means a value of type X or the value None and is equivalent to typing.Optional[X]. It does not mean an argument can be omitted: only a default value, such as value: int | None = None, allows omission in a call. Annotations do not automatically check or convert arguments at runtime; the code must handle None itself.

Member order does not affect union equality, and duplicates are removed: int | str == str | int and int | str | int == int | str. Unions can be used with isinstance() and issubclass(), but parameterized types such as list[int] are not valid for those checks. The check isinstance([1], int | list[int]) raises TypeError.

When evaluating a union expression at runtime, do not mix a type with a string reference to a class: int | "Foo" fails. If an annotation needs such a reference, quote the whole expression: "int | Foo". In the example, describe explicitly handles None, then converts the remaining values to text.

Reference identifiers covered by this entry: X | None / X | Y type union.

Examples

def describe(value: int | str | None) -> str:
    if value is None:
        return "missing"
    return str(value)

print(describe(7))
print(describe("hello"))
print(describe(None))
print(isinstance("hello", int | str))

Result

7
hello
missing
True

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