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¶
Baseline Performance¶
Python 3.10 is the oldest version covered by this site; later releases build on it:
# 3.10: similar performance to earlier 3.x releases
# 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¶
Core data structures have the same complexity as earlier 3.x releases:
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 | Hash-based removal |
key in d |
O(1) avg | Hash-based lookup |
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 Older Releases¶
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:
# Older 3.x code generally works on 3.10
# New features (pattern matching) optional
Other Notable Features¶
Type Hints Without Imports¶
# Can use list, dict directly (no typing imports needed)
def process(items: list[int]) -> dict[str, int]:
return {str(i): i for i in items}
# Plus the | operator for unions
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¶
Minor additions over earlier releases.
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 3.11+ instead if: - ✅ Performance critical (inline caching, 10-60% faster) - ✅ You want exception groups and fine-grained error locations
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
Related Documentation¶
- Python 3.11 - Better choice for performance
- Python 3.12