Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Typing & static analysisMiddleCommonPractical

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

Python example
def find_user(id: int) -> User | None:

is the modern equivalent of

Python example
def find_user(id: int) -> Optional[User]:

, both telling a caller the function might return `None` .

#typing#optional#syntax

Sources

typing — Support for type hintsPython Software Foundation · Generics, protocols, overloads and typing-module semanticsWhat's new in Python 3.14Python Software Foundation · Current-version language and runtime changes, including template strings and free-threading support