Python Snippet

Optional, Union, Literal Type Hints

Difficulty: Easy

Modern Python type hints (3.10+) replaced most of `typing.Optional` and `typing.Union` with the `X | Y` operator and made `Literal` the right tool for closed string sets. This entry covers `T | None` for nullable values, `X | Y` for unions, and `Literal['a', 'b']` for enum-like APIs, with runtime examples that show why each shape matters.

Code Snippets
/

Optional, Union, Literal Type Hints

Optional, Union, Literal Type Hints

Modern Python type hints (3.10+) replaced most of `typing.Optional` and `typing.Union` with the `X | Y` operator and made `Literal` the right tool for closed string sets. This entry covers `T | None` for nullable values, `X | Y` for unions, and `Literal['a', 'b']` for enum-like APIs, with runtime examples that show why each shape matters.

Python
Easy
3 snippets
py-type-hints
py-standard-library

960 views

11

T | None is the modern way to say 'either a T or None'. It is exactly equivalent to Optional[T] from the typing module, but reads more like English and avoids the import. The pattern is the right shape for 'lookup that might miss', 'value that has not been computed yet', and any boundary where None is a real, valid case. Always pair the return type with an is not None check at the call site so the type checker can narrow the value to T inside the branch.