What is the difference between `Optional[X]` and `X | None`, and why is the `|` union syntax now preferred?
Answer
`Optional[X]` is exactly equivalent to `Union[X, None]`: it means the value is either type `X` or `None`. Since PEP 604 in Python 3.10, `X | None` (and more generally `X | Y` for any union) expresses the same thing with built-in operator syntax that needs no import from `typing` at all, reads more naturally, and works directly on ordinary built-in types like `list[int] | None` instead of the older, more verbose `Optional[List[int]]` that required importing `List` from `typing` on Python versions before 3.9.
Strong answer includes
- Optional[X] is exactly Union[X, None]
- X | None syntax from PEP 604 (3.10) needs no typing import
- reads more naturally and composes with plain built-in generics
Practical example
def find_user(id: int) -> User | None:is the modern equivalent of
def find_user(id: int) -> Optional[User]:, both telling a caller the function might return `None` .