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

961 views

11

def find_user(user_id: int) -> dict | None:
    """Return the user dict, or None if no user has that id."""
    db = {1: {'name': 'ana'}, 2: {'name': 'ben'}}
    return db.get(user_id)

user = find_user(1)
if user is not None:
    print(user['name'])

missing = find_user(999)
print(missing)  # None

# Pre-3.10 you would write `Optional[dict]` from typing.
from typing import Optional

def legacy(user_id: int) -> Optional[dict]:
    return None  # exact same meaning as `dict | None`

print(legacy.__annotations__)  # {'user_id': <class 'int'>, 'return': typing.Optional[dict]}

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.