0
0
PythonConceptBeginner · 3 min read

Union Type in Python: What It Is and How to Use It

In Python, a union type allows a variable to hold values of multiple specified types, improving code flexibility and clarity. It is created using the typing.Union or the simpler | operator in Python 3.10 and later.
⚙️

How It Works

Think of a union type like a box that can hold different kinds of items, but only certain types you allow. For example, you might have a box that can hold either apples or oranges, but nothing else. In Python, a union type lets you say a variable can be one type or another, like a number or a string.

This helps when you want your code to accept different kinds of inputs but still keep things clear and safe. Python uses special syntax to show this: before Python 3.10, you used typing.Union, and from Python 3.10 onward, you can use the simpler | symbol between types. This makes your code easier to read and understand.

💻

Example

This example shows how to use a union type to accept either an integer or a string in a function.
python
from typing import Union

def greet(name: Union[str, int]) -> str:
    return f"Hello, {name}!"

print(greet('Alice'))
print(greet(123))
Output
Hello, Alice! Hello, 123!
🎯

When to Use

Use union types when your code needs to handle more than one type of data in the same place. For example, if a function can accept either a number or a string, union types make this clear and safe.

This is common in real-world programs where inputs can vary, like reading user input that might be text or numbers, or working with data that can come in different formats. Union types help you write code that is flexible but still easy to understand and check for errors.

Key Points

  • Union types let variables hold values of multiple specified types.
  • Use typing.Union before Python 3.10, or the | operator in Python 3.10+.
  • They improve code clarity and help catch type errors early.
  • Useful when functions or variables can accept different kinds of data.

Key Takeaways

Union types allow variables to hold values of multiple types for flexibility.
Use the | operator for union types in Python 3.10 and later for simpler syntax.
Union types improve code readability and help prevent type errors.
They are ideal when inputs or variables can be more than one type.