Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Optional vs Union: Choosing the Right Type Hint

Understand how Python's Optional and Union type hints relate, including when to use each for clearer code and type checking.

~5 min readPython
#type hints#typing module#Optional#Union
Diagram comparing Python Optional and Union type hints, showing Optional as a single type with a None branch and Union as multiple types merging.

When you write type hints in Python, you sometimes need to express that a value can be either a specific type or None. The typing module provides two ways to do this: Optional[T] and Union[T, None]. They are closely related: Optional[T] is shorthand for Union[T, None]. This article explains the practical differences, when to use each form, and how they behave in type checking and at runtime.

The Relationship Between Optional and Union

Optional is defined as a special case of Union. Optional[X] is equivalent to Union[X, None], so the following two type hints are identical:

python
from typing import Optional, Union def fetch_user(user_id: int) -> Optional[str]: ... def fetch_user(user_id: int) -> Union[str, None]: ...

Both functions return either a string or None. Type checkers treat them the same way. The difference is stylistic and semantic: Optional signals that the value can be absent, typically because the operation may fail or the data may not exist. Union signals that the value can be one of several distinct types, with None just one of the possibilities.

When to Use Optional

Use Optional[T] when the only alternative to a value of type T is None. This is common for parameters that may be omitted (with a default of None), return values that may not exist, or attributes that are uninitialized. For example:

python
from typing import Optional def find_user(email: str) -> Optional[dict]: # Returns a user dict or None if not found ... def send_email(to: str, subject: str, body: Optional[str] = None) -> None: # body is optional, defaults to None ...

Optional makes the intent explicit: the value is either present or explicitly None. It is shorter than Union[T, None], and the Python typing documentation and common style guides recommend it when None is the only alternative.

When to Use Union

Use Union when a value can be one of several distinct types, and None is not necessarily the only alternative. For example, a function that accepts an identifier that could be an integer or a string:

python
from typing import Union def lookup(value: Union[int, str]) -> str: ...

Union is also appropriate when None is one of several possible values, but the other types are not all related to a single concept. For instance, a function that returns a parsed result, an error message, or None:

python
from typing import Union def parse_input(raw: str) -> Union[dict, str, None]: # Returns dict on success, error message on failure, or None if empty ...

Here, Optional[dict] would be insufficient because the function can also return a string. Union keeps all alternatives at the same level and describes the full set of possible return types. If there are multiple non-None types, Union is usually the clearest form, though you can also write Optional[Union[dict, str]] if you want to separate the meaningful values from the absence case.

Type Checking Behavior and Tooling

From the perspective of static type checkers, Optional[T] and Union[T, None] are interchangeable. Mypy, pyright, and other tools treat them as equivalent, so switching between the two does not change type checking results. Error messages may display a type as Optional[T] because checkers often normalize to the shorter form.

One syntactic difference is that Optional takes a single type argument. Optional[Union[int, str]] is valid and equivalent to Union[int, str, None], but if you want to write all alternatives at the same level, use Union.

Runtime validation libraries may also inspect these annotations. In Pydantic, for example, both Optional[T] and Union[T, None] allow T or None as input. If you generate JSON schemas from Pydantic models, check the schema output for the version you use, since some versions may represent nullable unions differently.

Common Pitfalls and Misconceptions

A common misunderstanding is that Optional[T] means the argument itself can be omitted from a function call. This is not true. Optional[T] only indicates that the value can be None; it does not affect whether the argument has a default value. For example:

python
from typing import Optional def greet(name: Optional[str]) -> str: return f"Hello, {name or 'there'}" greet() # TypeError: missing required argument

Even though name is Optional[str], the function still requires an argument. To make the argument optional, provide a default value, typically None:

python
def greet(name: Optional[str] = None) -> str: ...

Another misconception is that Optional is a distinct runtime type from Union. In Python's typing module, Optional[int] and Union[int, None] produce equivalent objects:

python
from typing import Optional, Union print(Optional[int] == Union[int, None]) # True

There is no runtime difference between the two forms. The choice is about code clarity and intent.

Runtime Behavior and Performance

Type hints are not enforced at runtime by default. They are used by static type checkers and IDEs. At runtime, Optional[T] and Union[T, None] are just objects from the typing module, so there is no meaningful performance cost from choosing one over the other.

The situation changes if you use a runtime validation library such as typeguard or pydantic. Those libraries inspect annotations and may treat Optional[T] and Union[T, None] as equivalent, but some library versions or schema generators may represent the two forms differently in generated schemas. If that matters for your API output, test with the library version you use before relying on one form.

Maintainability and Code Clarity

The primary reason to choose between Optional and Union is clarity. Optional[T] is shorter and immediately signals that None is a valid value. Union[T, None] is more explicit about None being one of several possible types.

A consistent style helps developers understand intent quickly. For example:

python
from typing import Optional, Union # Clear: value is either a string or None def get_config(key: str) -> Optional[str]: ... # Clear: value is one of three distinct types def parse_data(raw: str) -> Union[dict, list, None]: ...

When you see Optional, you know the function returns a single type or None. When you see Union, you know there are multiple possible types, and None may be one of them. This distinction can make function contracts easier to review.

Some teams write Optional[Union[dict, list]] instead of Union[dict, list, None] to separate the union of meaningful types from absence:

python
from typing import Optional, Union def load_data() -> Optional[Union[dict, list]]: ...

This reads as "a dict or list, or None". Both forms are valid; choose the one that is more readable in your context.

Edge Cases and Advanced Usage

If a type is already a union, adding None with Optional can be written two ways. Optional[Union[int, str]] and Union[int, str, None] are equivalent. The first makes absence stand out; the second keeps all alternatives at the same level. In complex signatures, pick the form that best communicates the function's contract.

Finally, type narrowing works the same way for both forms. A check like if x is None narrows the value correctly whether the annotation was written as Optional[T] or Union[T, None]. With a multi-type Union, you may need to narrow each non-None type explicitly, but adding None to the union does not change how narrowing works.

Choosing the Right Type Hint

In practice, the choice is about expressing intent. Use Optional when None is the only alternative and the concept is best described as an optional value. Use Union when the value can be one of several distinct types, and None is just one possibility. This simple rule keeps type hints readable and maintainable across a codebase.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.