Skip to content

How to Fix Python TypeError with Union Types

DodaTech 2 min read

In this tutorial, you'll learn about How to Fix Python TypeError with Union Types. We cover key concepts, practical examples, and best practices.

The Problem

You see TypeError: unsupported operand type(s) for |: 'type' and 'type' when using int | str union syntax in Python versions below 3.10 that do not support the pipe operator for types. This commonly happens when writing modern type annotations on an older interpreter.

Quick Fix

Use typing.Union for Python < 3.10

python3 -c "
from typing import Union

def greet(name: Union[str, None]) -> str:
    return f'Hello {name}' if name else 'Hello'

print(greet('World'))
"
# Hello World

Replace str | None with Union[str, None] for compatibility with Python 3.7 through 3.9. This is the standard approach for code that must run on multiple Python versions.

Use Optional for Nullable Types

python3 -c "
from typing import Optional

def find_user(uid: int) -> Optional[str]:
    return 'Alice' if uid == 1 else None

print(find_user(1))
print(find_user(2))
"
# Alice
# None

Optional[X] is shorthand for Union[X, None] and is the idiomatic way to express a value that may be absent. It makes the intent of the code clearer.

Upgrade to Python 3.10+ for Pipe Syntax

python3.10 -c "
def process(data: int | str) -> str:
    return f'Got {data}'

print(process(42))
print(process('hello'))
"
# Got 42
# Got hello

Python 3.10 introduced X | Y as a concise syntax for union types that works at runtime for isinstance() checks too, making it more than just a typing annotation.

Verify Your Python Environment

python3 --version
# Python 3.10.12
pip list | grep requests
# requests            2.31.0

Check your Python version and installed packages before debugging. Many errors are caused by version mismatches between development and production environments. Using a virtual environment with pinned dependencies prevents these surprises.

Additional Troubleshooting

# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"

If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.

Use Type Aliases for Complex Unions

python3 -c "
from typing import Union, List
JSONValue = Union[str, int, float, bool, None, List['JSONValue']]
def process(data: JSONValue) -> str:
    return f'Got {type(data).__name__}'
print(process(42))
print(process('text'))
"
# Got int
# Got str

Define type aliases for complex Union types that are used in multiple places. This keeps your type annotations readable and consistent across your codebase.

Prevention

  • Check your Python version with python3 --version before using the pipe union syntax
  • Use from __future__ import annotations to make all annotations strings (lazy evaluation) in Python 3.7+
  • Install typing_extensions for access to newer typing features on older Python versions
  • Run mypy or pyright during CI to catch type errors before they reach production

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro