Union typing is only needed when you have a statically typed language, as you need to declare that an object can return one of multiple types (in your case an int or str, or in the other example str or NoneType).

Python deals in objects only, so there is never a need to even consider 'union types'. Python functions return what they return, if the programmer wants to return different types for different results then that's their choice. The choice is then an architecture choice, and makes no difference to the Python interpreter (so there is nothing to 'benchmark' here).

Python 3.5 does introduce a standard for creating optional type hints, and that standard includes Union[...] and Optional[...] annotations. Type hinting adds optional static type checking outside of the runtime, the same way types in TypeScript are not part of the JavaScript runtime.

Answer from Martijn Pieters on Stack Overflow
🌐
Python documentation
docs.python.org β€Ί 3 β€Ί library β€Ί typing.html
typing β€” Support for type hints
To define a union, use e.g. Union[int, str] or the shorthand int | str. Using that shorthand is recommended. Details: The arguments must be types and there must be at least one.
🌐
Python
peps.python.org β€Ί pep-0604
PEP 604 – Allow writing union types as X | Y | peps.python.org
annotation: name_type name_type: NAME (args)? args: '[' paramslist ']' paramslist: annotation (',' annotation)* [','] To describe a disjunction (union type), the user must use Union[X, Y].
🌐
Medium
medium.com β€Ί @wrefordmessi β€Ί advanced-python-typing-union-and-intersection-in-type-hints-45e7090e2a76
Advanced Python (Typing: Union and Intersection in Type Hints) | by Andrew Wreford Eshakz | Medium
April 6, 2023 - The Annotated[positive_integers, ... that are both positive and even. ... You can use the union typing to specify that a value can be of multiple types, while the intersection indicates that all types criteria must be satisfied ...
🌐
Python.org
discuss.python.org β€Ί typing
How do I hint a function that returns a union of types - Typing - Discussions on Python.org
July 23, 2025 - Hello, I have a function which builds a union based on a tuple of types that gets passed in. Programmatically this works fine, but how do I create a proper type hint? I expected this to work, since in the docs it mentions t hat the TypeVarTuple can be used anywhere a normal TypeVar.
🌐
Python
peps.python.org β€Ί pep-0484
PEP 484 – Type Hints | peps.python.org
Since the subclasses of Enum cannot be further subclassed, the type of variable x can be statically inferred in all branches of the above example. The same approach is applicable if more than one singleton object is needed: one can use an enumeration that has more than one value: class Reason(Enum): timeout = 1 error = 2 def process(response: Union[str, Reason] = '') -> str: if response is Reason.timeout: return 'TIMEOUT' elif response is Reason.error: return 'ERROR' else: # response can be only str, all other possible values exhausted return 'PROCESSED: ' + response
🌐
FastAPI
fastapi.tiangolo.com β€Ί python-types
Python Types Intro - FastAPI
These "type hints" or annotations are a special syntax that allow declaring the type of a variable. By declaring types for your variables, editors and tools can give you better support. This is just a quick tutorial / refresher about Python type hints. It covers only the minimum necessary to use them with FastAPI...
🌐
Python
docs.python.org β€Ί 3.10 β€Ί library β€Ί typing.html
typing β€” Support for type hints β€” Python 3.10.19 documentation
To define a union, use e.g. Union[int, str] or the shorthand int | str. Using that shorthand is recommended. Details: The arguments must be types and there must be at least one.
Find elsewhere
🌐
Mouse Vs Python
blog.pythonlibrary.org β€Ί home β€Ί python 3.10 - simplifies unions in type annotations
Python 3.10 - Simplifies Unions in Type Annotations - Mouse Vs Python
September 11, 2021 - In Python 3.10, you no longer need to import Union at all. All the details are in PEP 604. The PEP allows you to replace it entirely with the | operator. Once you have done that, the code above becomes the following: def square(number: int | float) -> int | float: return number ** 2 Β· You can use the new syntax to replace Optional as well, which is what you used for type hinting that an argument could be None:
🌐
Mypy
mypy.readthedocs.io β€Ί en β€Ί stable β€Ί cheat_sheet_py3.html
Type hints cheat sheet - mypy 1.19.1 documentation
# You can use the ClassVar annotation to declare a class variable class Car: seats: ClassVar[int] = 4 passengers: ClassVar[list[str]] # If you want dynamic attributes on your class, have it # override "__setattr__" or "__getattr__" class A: # This will allow assignment to any A.x, if x is the same type as "value" # (use "value: Any" to allow arbitrary types) def __setattr__(self, name: str, value: int) -> None: ... # This will allow access to any A.x, if x is compatible with the return type def __getattr__(self, name: str) -> int: ... a = A() a.foo = 42 # Works a.bar = 'Ex-parrot' # Fails type checking Β· from typing import Union, Any, Optional, TYPE_CHECKING, cast # To find out what type mypy infers for an expression anywhere in # your program, wrap it in reveal_type().
🌐
Quora
quora.com β€Ί Which-is-better-when-type-hinting-in-Python-Union-type1-type2-or-type1-type2
Which is better when type hinting in Python, β€œUnion [type1, type2]” or β€œtype1 | type2”? - Quora
Answer (1 of 2): I think the trend is moving towards [code ]type1 | type2[/code], which is the newer, more concise form. This form is used in TypeScript as well, and is similar to how tagged unions are defined in languages like ML and Haskell. While perhaps not quite as obvious as spelling out t...
🌐
Playful Python
playfulpython.com β€Ί type-hinting-union-and-sum-types
Type Hinting: Union and Sum types
April 20, 2023 - You can easily represent this type of parameter using a union type and mypy will happily validate that the type is not violated by any of the callers. It is a very powerful feature, especially in a dynamic language like Python where these kinds of functions are very common.
🌐
Adam Johnson
adamj.eu β€Ί tech β€Ί 2022 β€Ί 10 β€Ί 17 β€Ί python-type-hints-old-and-new-syntaxes
Python type hints: old and new ways to write the same types - Adam Johnson
As type hints have evolved, Python ... since Mypy uses them when reporting types. A union type combines several types, expressing that a value may be any one of those types....
🌐
CodersLegacy
coderslegacy.com β€Ί home β€Ί python β€Ί python union in typing – specify multiple types
Python Union in Typing - Specify Multiple Types - CodersLegacy
February 25, 2022 - Python 3.5 introduced the concept of Typing Hinting as well as the typing library, where as we could specify a static type for variables and functions. Amongst the various features introduced in the Python Typing library, was the use of the Union function, which can be used to specify multiple possible types for a variable or function.
🌐
Python
docs.python.org β€Ί 3.9 β€Ί library β€Ί typing.html
typing β€” Support for type hints β€” Python 3.9.24 documentation
To define a union, use e.g. Union[int, str]. Details: The arguments must be types and there must be at least one.
🌐
Python
docs.python.org β€Ί 3.8 β€Ί library β€Ί typing.html
typing β€” Support for type hints β€” Python 3.8.20 documentation
To define a union, use e.g. Union[int, str]. Details: The arguments must be types and there must be at least one.
Top answer
1 of 2
7

If you import

from __future__ import annotations

you can use the union types with | syntax starting from Python 3.7, without errors.

$ python3.7 -c 'from __future__ import annotations; a: int | str = 42'

If you don't use the __future__ import to enable new PEP 563 behavior, Python evaluates the annotations at runtime and you get an exception because prior to 3.10, types don't define the | operator.

When using __future__ import, you need to rely on your IDE or running mypy to catch incorrectly formatted annotations. Use sufficiently new mypy that supports this new syntax.

(For reference, here's what happens without the __future__ import.)

$ python3.7 -c 'a: int | str = 42'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'type' and 'type'
2 of 2
4

PEP 604, which was implemented in Python 3.10 allows Union types to be formed using the | operator (which has existed with exclusively numeric meanings for most of Python's history).

So in sufficiently recent versions of Python, you can write your type hint like this, with no imports required from typing:

some_stuff: list[int|str|float|list[str]] = [98, "Fido", -34.925, ["Phantom", "Tollbooth"]]

While that specifically answers your question, I'd note that it's a little suspicious that your example data exactly matches the order of the types you're listing in the Union. If you are always going to have exactly one of each kind of data (rather than some unknown mixture of them), you probably want to be type hinting the value differently, e.g. with tuple[int, str, float, list[str]] which specifies that there will be one value of each, in that order. You might need to use an actual tuple for the value, I'm not sure there's a way to hint a fixed pattern of values within a list object.

🌐
mypy
mypy.readthedocs.io β€Ί en β€Ί latest β€Ί kinds_of_types.html
Kinds of types - mypy 1.20.0+dev.1d8ddd5949c3ce1af6ba5ef7adee841740a1691c documentation
Instead, you can use the legacy Union[T1, ..., Tn] type constructor. Example: from typing import Union def f(x: Union[int, str]) -> None: ... It is also possible to use the new syntax with versions of Python where it isn’t supported by the runtime with some limitations, if you use from __future__ import annotations (see Annotation issues at runtime):
🌐
Pythonpapers
pythonpapers.com β€Ί p β€Ί simplifying-unions-in-python-type
Simplifying Unions in Python Type Hints - by Mike Driscoll
February 21, 2024 - Python 3.10 has several new typing features. They are given in detail here: ... This tutorial focuses on talking about PEP 604, which makes writing union types easier when adding type annotation (AKA: type hinting) to your codebase.