liveBook · Manning

Union type

As explained in Python How-To

A union type specifies that a value may belong to one of several permitted data types.

A union type lets a function parameter accept one of several permitted data types. In modern Python type hints, separate alternatives with the vertical bar (|), such as int | float | str. section 6.3.3

Accepting a list or tuple

A statistics function can accept either a list of floating-point values or a tuple containing multiple floating-point values:\n\ndef generate_stats(measures: list[float] | tuple[float, ...]) -> tuple[float, float]:\n measure_mean = mean(measures)\n measure_std = stdev(measures)\n return measure_mean, measure_std\n\nThe union documents both supported forms while the return annotation describes the resulting pair. section 6.3.3

Use the same notation in several common situations:

  • Place a union inside a container annotation, such as set[int | str], when the container may hold either type. section 6.3.5
  • Combine complete container types, such as list[int] | list[str], when the function accepts either a list of integers or a list of strings. section 6.3.5

Precise union annotations help IDEs identify incompatible arguments during development. The syntax belongs to evolving features in recent Python versions, so availability depends on the Python version in use. section 6.3.3

How Python How-To covers it

How deep it goes
Explains vertical-bar syntax, nested container annotations, and IDE feedback without covering runtime validation.
Examples
Uses statistics over a list-or-tuple parameter, multiway annotations, and unions nested inside set or list annotations.
What it assumes
Assumes familiarity with Python functions and basic type hints, then extends container annotations to multiple alternatives.
What you can do after
Apply it via Python type hints to document flexible function parameters and receive development-time incompatibility warnings.
How it connects
Connects function definitions with type hints, container types, and IDE code analysis.

Also explained in

Compare how 10 books explain union type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.