Modern union and Optional syntax: X | Y
suggest changePython 3.10 (PEP 604) lets you write union types with the | operator:
int | strinstead ofUnion[int, str]int | Noneinstead ofOptional[int]
The new spelling needs no import from typing, reads like the "or" it means, and also works at runtime, for example in isinstance(x, int | str).
This article covers the syntax, how it relates to typing.Union and typing.Optional, what a union object is at runtime, the places where | doesn't work (string forward references, parameterized generics in isinstance), and how to convert old code automatically. How to handle values that may be None (narrowing, sentinels, defaults) is covered in None and Optional.
Examples were run with Python 3.13, except where Python 3.14 is mentioned. Type checker output is from mypy 2.4.
Writing unions with |
Use | anywhere you'd write a type hint: parameters, return values, variables, and inside generic types:
def parse_port(value: str | int) -> int | None:
if isinstance(value, int):
return value
return int(value) if value.isdigit() else None
print(parse_port(8080))
print(parse_port("443"))
print(parse_port("http"))
scores: dict[str, list[int | None]] = {"ann": [90, None, 85]}
print(scores)
8080
443
None
{'ann': [90, None, 85]}
A union can have any number of members, and members can be generic types, Literal, None or anything else a type hint accepts:
from typing import Any, Literal
print(None | int)
print(list[int] | None)
print(Literal["r", "w"] | None)
print(int | Any)
None | int
list[int] | None
typing.Optional[typing.Literal['r', 'w']]
int | typing.Any
On Python 3.13 a union that contains a typing special form such as Literal still prints in the old typing.Optional[...] style; Python 3.14 prints typing.Literal['r', 'w'] | None.
None can appear on either side; None | int and int | None mean the same thing. The convention is to put None last.
X | Y is the same as Union and Optional
int | str and Union[int, str] are the same type, and int | None is the same as Optional[int]. They compare equal at runtime, and type checkers treat them identically, so you can mix old and new code freely:
from typing import Optional, Union
print(int | str)
print(int | None)
print(int | str == Union[int, str])
print(int | None == Optional[int])
print(int | str == str | int)
print(int | str | int)
print((int | str) | (str | float))
print(int | int)
int | str
int | None
True
True
True
int | str
int | str | float
<class 'int'>
Unions follow the same rules as Union[...]:
- order doesn't matter for equality:
int | str == str | int - duplicates are removed:
int | str | intisint | str - nested unions are flattened:
(int | str) | (str | float)isint | str | float - a union of one type is just that type:
int | intisint
There is no | replacement for the word "Optional", and that's a good thing. Optional[int] suggests "an optional argument", but it only means "may be None". int | None says exactly that. If the argument can also be omitted, give it a default: timeout: float | None = None.
Union and Optional are not deprecated and still work, but new code should use |. Linters such as ruff flag the old forms when your minimum Python version is 3.10 or newer (see the last section).
Unions at runtime
int | str is an ordinary expression: type.__or__ builds a union object. On Python 3.10 to 3.13 that object is a types.UnionType, while Union[int, str] creates a different class from the typing module:
import types
import typing
u = int | str | None
print(type(u))
print(u.__args__)
print(typing.get_args(u))
print(typing.get_origin(u))
old = typing.Union[int, str]
print(type(old))
print(old)
print(typing.get_origin(old))
<class 'types.UnionType'>
(<class 'int'>, <class 'str'>, <class 'NoneType'>)
(<class 'int'>, <class 'str'>, <class 'NoneType'>)
<class 'types.UnionType'>
<class 'typing._UnionGenericAlias'>
typing.Union[int, str]
typing.Union
typing.get_args() returns the members of either kind of union. Note that None is stored as NoneType.
Python 3.14 merges the two: typing.Union and types.UnionType are now the same class, Union[int, str] creates the same object as int | str, and both print as int | str. The same script on Python 3.14:
<class 'typing.Union'>
(<class 'int'>, <class 'str'>, <class 'NoneType'>)
(<class 'int'>, <class 'str'>, <class 'NoneType'>)
<class 'typing.Union'>
<class 'typing.Union'>
int | str
<class 'typing.Union'>
If you write code that inspects annotations (a serializer, a CLI parser, a dependency injection container) and must support Python versions before 3.14, check for both origins:
import types
import typing
def is_union(tp) -> bool:
return typing.get_origin(tp) in (typing.Union, types.UnionType)
print(is_union(int | str))
print(is_union(typing.Optional[int]))
print(is_union(list[int]))
print(types.UnionType is typing.Union)
True
True
False
False
The last line prints True on Python 3.14.
isinstance and issubclass
Since union types are runtime objects, isinstance() and issubclass() accept them in place of a tuple of types:
def describe(value: object) -> str:
if isinstance(value, int | float):
return f"number {value}"
if isinstance(value, str | bytes):
return f"text {value!r}"
if value is None:
return "nothing"
return "something else"
for v in [3, 2.5, "hi", b"raw", None, [1]]:
print(describe(v))
print(issubclass(bool, int | str))
print(isinstance(None, int | None))
number 3
number 2.5
text 'hi'
text b'raw'
nothing
something else
True
True
isinstance(x, int | float) means the same as isinstance(x, (int, float)). Pick whichever you like. The tuple form is a little faster when the union is written inline in a hot loop, because int | float builds a new union object on every call. Storing the union in a module-level constant avoids that.
isinstance() can only check classes, not parameterized generics. A union that contains list[int] is rejected, the same way isinstance(x, list[int]) is:
try:
isinstance([1], list[int] | None)
except TypeError as e:
print("TypeError:", e)
print(isinstance([1], list | None))
TypeError: isinstance() argument 2 cannot be a parameterized generic
True
In a match statement the equivalent of a union is an or-pattern of class patterns. Type checkers understand both forms and narrow the type in each branch. More on match in Pattern matching:
def kind(value: int | float | str | None) -> str:
match value:
case int() | float():
return "number"
case str():
return "text"
case None:
return "missing"
print(kind(1), kind(2.5), kind("a"), kind(None))
number number text missing
functools.singledispatch
Since Python 3.11, functools.singledispatch (and singledispatchmethod) accepts union annotations, so one implementation can handle several types:
from functools import singledispatch
@singledispatch
def to_text(value: object) -> str:
return f"<{type(value).__name__}>"
@to_text.register
def _(value: int | float) -> str:
return f"number {value:g}"
@to_text.register
def _(value: list | tuple) -> str:
return ", ".join(to_text(v) for v in value)
@to_text.register
def _(value: str) -> str:
return repr(value)
print(to_text(42))
print(to_text(0.25))
print(to_text([1, (2.5, "x")]))
number 42
number 0.25
number 1, number 2.5, 'x'
Type checkers and unions
With a union type, a type checker only lets you do what is valid for every member. isinstance, is None checks and match narrow the type to the matching members:
def area(shape: tuple[float, float] | float) -> float:
reveal_type(shape)
if isinstance(shape, tuple):
reveal_type(shape)
w, h = shape
return w * h
reveal_type(shape)
return 3.14159 * shape**2
def shout(text: str | None) -> str:
return text.upper()
$ mypy app.py
app.py:2: note: Revealed type is "tuple[float, float] | float"
app.py:4: note: Revealed type is "tuple[float, float]"
app.py:7: note: Revealed type is "float"
app.py:11: error: Item "None" of "str | None" has no attribute "upper" [union-attr]
Found 1 error in 1 file (checked 1 source file)
reveal_type() is understood by type checkers; at runtime it's available as typing.reveal_type (Python 3.11+).
Type aliases
Long unions are easier to read with a name. A plain assignment creates an alias that works both as a type hint and at runtime. Python 3.12 added the type statement, which is evaluated lazily and allows recursive aliases:
from typing import TypeAlias
Number: TypeAlias = int | float
PathLike = str | bytes # an implicit alias works too
type Json = dict[str, Json] | list[Json] | str | int | float | bool | None
def total(values: list[Number]) -> Number:
return sum(values)
print(total([1, 2.5, 3]))
print(Number, PathLike)
print(Json, Json.__value__)
print(isinstance(2.5, Number))
6.5
int | float str | bytes
Json dict[str, Json] | list[Json] | str | int | float | bool | None
True
Number is the union object itself, so isinstance(2.5, Number) works. An alias made with type is a TypeAliasType, which isinstance() doesn't accept.
Forward references and from __future__ import annotations
| is evaluated like any other operator. That causes two problems in annotations.
A string forward reference can't be combined with |. A class can't refer to itself by name in its own body, so you'd normally quote it: "Node". But "Node" | None tries to apply | to a str:
class Node:
def __init__(self, value: int, next: "Node" | None = None):
self.value = value
self.next = next
Traceback (most recent call last):
...
def __init__(self, value: int, next: "Node" | None = None):
~~~~~~~^~~~~~
TypeError: unsupported operand type(s) for |: 'str' and 'NoneType'
Quote the whole annotation instead:
class Node:
def __init__(self, value: int, next: "Node | None" = None):
self.value = value
self.next = next
print(Node.__init__.__annotations__)
{'value': <class 'int'>, 'next': 'Node | None'}
Or add from __future__ import annotations at the top of the module. It turns every annotation into a string that is never evaluated at runtime, so no quotes are needed:
from __future__ import annotations
class Node:
def __init__(self, value: int, next: Node | None = None):
self.value = value
self.next = next
print(Node.__init__.__annotations__)
{'value': 'int', 'next': 'Node | None'}
Older Python versions don't have type.__or__. On Python 3.9 and earlier, int | None in an annotation raises TypeError: unsupported operand type(s) for |: 'type' and 'NoneType'. from __future__ import annotations (available since 3.7) lets you use X | Y in annotations on those versions too, because type checkers read the strings but Python never evaluates them. It only covers annotations, though. On 3.9 these still fail, because they are ordinary expressions:
- type aliases:
Number = int | float isinstance(x, int | str)andcast(int | None, x)- libraries that evaluate annotations at runtime with
typing.get_type_hints(), such as pydantic orfunctools.singledispatch
If you must support Python 3.9, use Optional/Union in those places.
Python 3.14: no quotes needed
Python 3.14 evaluates annotations lazily (PEP 649), only when something asks for them. A forward reference written as Node | None works without quotes or a __future__ import:
class Node:
def __init__(self, value: int, next: Node | None = None):
self.value = value
self.next = next
print(Node.__init__.__annotations__)
On Python 3.13 this raises NameError: name 'Node' is not defined. On Python 3.14:
{'value': <class 'int'>, 'next': __main__.Node | None}
Unlike from __future__ import annotations, you get real union objects back, not strings. When you only target 3.14 and newer, you don't need the __future__ import for this anymore.
Converting old code
ruff (and pyupgrade, which it reimplements) rewrites Optional and Union automatically when the target version is 3.10 or newer. The relevant rules are UP007 (X | Y) and UP045 (X | None), and UP006 replaces List, Dict and friends with the built-in generics. Given old.py:
from typing import Dict, List, Optional, Union
def lookup(table: Dict[str, int], key: Optional[str]) -> Union[int, str, None]:
if key is None:
return None
return table.get(key, "missing")
def first(items: List[Union[int, float]]) -> Optional[float]:
return items[0] if items else None
and this pyproject.toml (F401 removes the imports that are no longer used):
[tool.ruff]
target-version = "py310"
[tool.ruff.lint]
select = ["UP", "F401"]
running ruff with --fix rewrites the file:
$ ruff check --fix old.py
Found 10 errors (10 fixed, 0 remaining).
def lookup(table: dict[str, int], key: str | None) -> int | str | None:
if key is None:
return None
return table.get(key, "missing")
def first(items: list[int | float]) -> float | None:
return items[0] if items else None
If the project declares requires-python = ">=3.10" in pyproject.toml, ruff picks up the target version from there and you can omit target-version.
Summary
| Old spelling | Modern spelling (3.10+) |
|---|---|
Union[int, str] |
int | str |
Optional[int] |
int | None |
Optional[Union[int, str]] |
int | str | None |
isinstance(x, (int, str)) |
isinstance(x, int | str) (both fine) |
"Node" inside Optional["Node"] |
"Node | None", or no quotes with from __future__ import annotations or on 3.14 |
Number = Union[int, float] |
Number = int | float or type Number = int | float (3.12) |
Things to remember:
X | YandUnion[X, Y]are the same type; mixing them is fine.- At runtime a union is a
types.UnionType(3.10-3.13) ortyping.Union(3.14+); usetyping.get_args()to read its members. isinstance()accepts unions of plain classes, not of parameterized generics likelist[int].- Never combine a quoted name with
|; quote the whole annotation.