Modern Python 3.10+ features
Python 3.10 introduced match/case (structural pattern matching), the walrus operator, and other modern syntax. You will see these in AI frameworks and open-source codebases. Since this course requires Python 3.10+, let us learn the modern way.
Python 3.10+ features
Key modern Python features for cleaner AI code
import re
# Walrus operator (:=) assigns and uses in one expression
text = "Error: API rate limit exceeded (code: 429)"
# Without walrus (two lines)
match = re.search(r"code: (\d+)", text)
if match:
print(f"Found error code: {match.group(1)}")
# With walrus (one line)
if (match := re.search(r"code: (\d+)", text)) is not None:
print(f"Found error code: {match.group(1)}")The walrus operator := assigns a value AND uses it in the same expression. It reduces repetition when you need to both check and use a value.
match/case is like a powerful switch statement that can match structure, not just values. It can destructure dicts and lists in one step. This is perfect for routing different API response shapes or tool calls in an agent.
# match/case: structural pattern matching
def handle_api_response(response):
match response:
case {"error": message}:
print(f"Error: {message}")
case {"choices": [{"message": {"content": text}}, *_]}:
print(f"Got response: {text[:50]}")
case {"status": "pending"}:
print("Still processing...")
case _:
print(f"Unknown format: {response}")
handle_api_response({"error": "Rate limit exceeded"})
handle_api_response({"choices": [{"message": {"content": "Hello!"}}]})
handle_api_response({"status": "pending"})
# Extended unpacking
models = ["gpt-4o", "claude-3.5-sonnet", "gemini-2.0-flash", "llama-3"]
first, *rest = models
print(f"Primary: {first}, Fallbacks: {rest}")
# Split system message from conversation
messages = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi there!"},
]
system_msg, *conversation = messages
print(f"System: {system_msg['content']}")
print(f"Conversation: {len(conversation)} messages")match/case destructures data in one step. Extended unpacking (first, *rest = list) splits lists cleanly. Both appear in modern AI code.
Quiz: Quiz
Loading practice…
Flashcards: Flashcards
Loading practice…
Validation checklist: Modern Python checklist
Loading practice…