Types

Union and Optional Types

The | operator describes values that may have more than one static type.

Use A | B when a value may have either type. The function body should use operations that make sense for every member of the union.

Source

def label(value: int | str) -> str:
    return f"item-{value}"

print(label(3))
print(label("A"))

Output

item-3
item-A
X: INT|STR|NONExintstrNone
`int | str | None` says one slot may hold any of three shapes — including expected absence.

str | None means the function accepts either a string or explicit absence. Check for None before calling string methods.

Source

def greeting(name: str | None) -> str:
    if name is None:
        return "hello guest"
    return f"hello {name.upper()}"

print(greeting(None))
print(greeting("Ada"))

Output

hello guest
hello ADA

Union annotations are visible at runtime, but Python does not enforce them when the function is called.

Source

print(greeting.__annotations__)

Output

{'name': str | None, 'return': <class 'str'>}

Notes

See also

Run the complete example

Example code

Expected output

item-3
item-A
hello guest
hello ADA
{'name': str | None, 'return': <class 'str'>}

Execution time appears here after you run the example.