Skip to content

Python 3.10 - Complexity & Optimizations

Python 3.10 was released October 2021 with pattern matching and improved performance.

Major Features

Structural Pattern Matching

# Match statements for elegant conditional logic
match value:
    case 1:
        print("one")
    case 2:
        print("two")
    case [x, y]:
        print(f"pair: {x}, {y}")
    case Point(x=0, y=0):
        print("origin")
    case _:
        print("default")

Union Type Operators

# Type hints with | operator
def process(value: int | str | list) -> None:
    if isinstance(value, int):
        # Handle int
        pass
    elif isinstance(value, str):
        # Handle str
        pass
    else:
        # Handle list
        pass

# Instead of: Union[int, str, list]

Performance Characteristics

Comparable to Python 3.9

Performance improvements minimal from 3.9:

# 3.10 vs 3.9: Similar performance
# New features (pattern matching) may have small overhead
# But optimizations offset it

# Example: Pattern matching
match value:
    case ...  # Slightly slower than if/elif for simple cases
    case ...  # But more readable

# For complex patterns: May be faster than if/elif chains

Data Structure Complexity

Same as Python 3.9:

Lists

Operation Complexity
append() O(1) amortized
insert() O(n)
pop() O(1)
pop(0) O(n)
sort() O(n log n)
in O(n)
index() O(n)

Dictionaries

Operation Complexity Notes
d[key] O(1) avg Order guaranteed; O(n) worst case with collisions
d[key] = v O(1) avg Insertion order preserved
del d[key] O(1) avg Same as 3.9
key in d O(1) avg Same as 3.9

Sets

Operation Complexity
add() O(1) avg
remove() O(1) avg
in O(1) avg
union O(n+m)
intersection O(min(n,m))
difference O(n)

Compatibility with 3.9

Minor Breaking Changes

# Changed behavior:
# - Some internal type details
# - Removed deprecated APIs
# - Changed error messages (slightly)

# Generally safe upgrade

Code Updates

Most code works without changes:

# 3.9 code works on 3.10
# New features (pattern matching) optional

Features from Python 3.9

Type Hints Without Imports

# Python 3.9: Can use list, dict directly
def process(items: list[int]) -> dict[str, int]:
    return {str(i): i for i in items}

# Python 3.10: Same, plus | operator
def process(items: list[int] | tuple[int, ...]) -> dict[str, int]:
    ...

Examples

Pattern Matching for Type Checking

def process_value(value):
    match value:
        case int():
            return value * 2
        case str():
            return value.upper()
        case [int(), int()] as pair:
            return sum(pair)
        case {"x": x, "y": y}:
            return Point(x, y)
        case _:
            return None

# vs if/elif chains - more readable

Matching Sequences

def analyze_list(lst):
    match lst:
        case []:
            print("empty")
        case [x]:
            print(f"single: {x}")
        case [x, y]:
            print(f"pair: {x}, {y}")
        case [x, *rest]:
            print(f"head: {x}, tail: {rest}")

# No performance penalty vs if/elif for same logic

Standard Library

Same as Python 3.9 with minor additions.

Recommendations

When to Use Python 3.10

Good for: - ✅ New projects (leverage pattern matching) - ✅ Complex conditional logic (cleaner code) - ✅ Type hint heavy code (| operator cleaner)

Consider staying on 3.9 if: - ✅ Performance critical (3.11 better choice) - ✅ Legacy code (careful testing needed) - ✅ Incompatible dependencies

Upgrade Strategy

# Test with 3.10
pyenv shell 3.10.x
pytest  # Run test suite

# Check for breakage
python -W all your_script.py

# If OK, upgrade
pyenv local 3.10.x

Performance Tips

Pattern Matching

Pattern matching not slower than equivalent if/elif:

# Bad: Many isinstance checks
if isinstance(x, int):
    result = x * 2
elif isinstance(x, str):
    result = x.upper()
else:
    result = None

# Good: Pattern matching (similar speed)
match x:
    case int():
        result = x * 2
    case str():
        result = x.upper()
    case _:
        result = None

# Same algorithmic cost, better readability