New Features in Python 3.11: Pattern Matching, Type Hints, Performance Optimizations, and More
This article introduces the major enhancements of Python 3.11—including structural pattern matching, improved type hints, faster execution via PEP 659, richer error messages, the new | dictionary‑merge operator, built‑in breakpoint debugging, and other standard‑library additions—illustrated with concise code examples.
Python 3.11 brings a substantial performance boost and a host of new language features that improve developer productivity and code reliability.
1. Pattern Matching
Python 3.11 introduces structural pattern matching, allowing concise handling of complex conditional logic.
def process_data(data):
match data:
case 0:
print("Received zero")
case [x, y]:
print(f"Received a list: {x}, {y}")
case {"name": name, "age": age}:
print(f"Received a dictionary: {name}, {age}")
case _:
print("Received something else")
process_data(0)
process_data([1, 2])
process_data({"name": "John", "age": 25})
process_data("Hello")2. Structural Pattern Matching
Extends pattern matching to whole data‑structure validation.
def process_nested_data(data):
match data:
case {"name": str, "age": int, "scores": [int, ...]}:
print("Valid data structure")
# further processing
case _:
print("Invalid data structure")
data = {"name": "John", "age": 25, "scores": [80, 90, 95]}
process_nested_data(data)
data = {"name": "Jane", "age": "twenty", "scores": [70, 85, 90]}
process_nested_data(data)3. Type Hints and Checking
Enhanced static type checking makes misuse of values evident at development time.
def add_numbers(a: int, b: int) -> int:
return a + b
result = add_numbers(5, 10)
print(result) # Output: 15
# The following line would raise a type‑check error
# result = add_numbers("Hello", "World")4. Performance Optimizations (PEP 659)
Optimized pattern‑matching machinery speeds up execution.
# PEP 659 optimized snippet
for i in range(1, 100):
match i:
case 5:
print("Found 5!")
case _:
pass5. Improved Error Reporting
Errors are now clearer and more actionable.
a = 10
b = "five"
result = a + b # Type mismatch error6. New Standard‑Library Modules
The zoneinfo module provides IANA time‑zone support.
from zoneinfo import ZoneInfo
from datetime import datetime
now = datetime.now(tz=ZoneInfo("Europe/London"))
print(now) # Example output: 2023-07-11 16:25:00+01:007. iterate Statement
A new syntactic sugar for iterating over collections.
my_list = [1, 2, 3]
iterate my_list:
print(item)
# Output:
# 1
# 2
# 38. Dictionary Merge Operator |
The | operator merges dictionaries in a concise way.
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = dict1 | dict2
print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}9. Built‑in breakpoint() Function
Provides a standard way to start the debugger without importing pdb .
def calculate_sum(a, b):
result = a + b
breakpoint() # Debugger breakpoint
return result
x = 5
y = 10
z = calculate_sum(x, y)
print(z)10. Synchronous Iteration with match
Combines match with zip to process multiple iterables simultaneously.
fruits = ["apple", "banana", "cherry"]
counts = [3, 6, 4]
for fruit, count in zip(fruits, counts):
match fruit, count:
case "apple", 3:
print("Three apples")
case "banana", 6:
print("Six bananas")
case "cherry", 4:
print("Four cherries")
case _:
print("Unknown fruit")Summary
Python 3.11 introduces a rich set of new features—pattern matching, refined type hints, better error messages, the | dictionary‑merge operator, built‑in debugging, and additional standard‑library modules—that enable developers to write more efficient, readable, and maintainable code, positioning it as the next mainstream Python version.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.