Nullable lookup results
A lookup may fail without raising an exception and returns None when no matching value exists.
Python · Type Alias
Optional[X] describes a value that may be either X or None. In modern Python, X | None is the equivalent spelling; Optional does not merely mean that an argument has a default.
Optional[X] annotates a value that may be an X or None. It describes whether None is an allowed value, not whether an argument may be omitted; in modern Python, X | None expresses the same type.
Optional[X]| Name | Type | Description |
|---|---|---|
X | type | X is the type that may be present instead of None. |
A type expression equivalent to Union[X, None], indicating that a value may be X or None.
from typing import Optional
def lookup_user(user_id: int) -> Optional[str]:
if user_id == 1:
return "Ada"
return None
print(lookup_user(1))
print(lookup_user(2))The return annotation allows either a string or None.
A lookup may fail without raising an exception and returns None when no matching value exists.
An API accepts an explicit null-like value alongside a concrete domain type.
A codebase supports Python versions before 3.10 and needs the older typing spelling.
Optional[X] means X or None, and it is equivalent to X | None or Union[X, None]. It is useful when a type checker should account for a possible None value.
Follow-up: When can the modern spelling be used? Python 3.10 added X | None as an alternative spelling.
No. Optional describes the set of permitted values, whereas an optional argument can simply mean an argument has a default. A parameter with a default does not need Optional unless None is also valid.
Follow-up: How would you annotate a parameter that has a default of 0 but must remain an integer? Use int, not Optional[int].
The annotation is not enforced by the Python runtime. Static type checkers, IDEs, and linters can use it to detect code that fails to handle the None case.
Follow-up: What should code do after receiving Optional[T]? Narrow or check the value before using operations that require T.
UnionAnyTypeVartype annotations