Types
Union and Optional Types
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-Astr | 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 ADAUnion 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
- Use
A | Bwhen a value may have either type. T | Nonemeans absence is an expected case, not an error by itself.- Narrow unions before using behavior that belongs to only one member type.
See also
- prerequisite: None
- related: Type Hints
- prerequisite: Match Statements
Run the complete example
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.