Skip to main content
Optional is a type hint from Python’s typing module used to indicate that a variable, argument, or return value can either be of a specified type T or the None singleton. Under the hood, Optional[T] is strictly a syntactic alias for Union[T, None].

Syntax and Implementation

To use Optional, it must be imported from the typing module and parameterized with a single concrete type.

Type Equivalence

Static type checkers (like mypy or pyright) treat Optional[T] and Union[T, None] as completely identical. The Optional keyword exists solely for developer readability.

Modern Syntax (Python 3.10+)

With the introduction of PEP 604 in Python 3.10, the bitwise OR operator (|) can be used to construct union types. This introduces T | None as the standard, built-in syntax, rendering the typing.Optional import largely obsolete in modern codebases.

Type vs. Parameter Requirement

A critical mechanical distinction in Python typing is that Optional[T] does not mean a function parameter can be omitted during invocation. It only dictates the allowed types for that parameter. To make a parameter truly optional to the caller, it must be assigned a default value.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More