Python course module guide: Control structures
Python match-case is a control-flow tool for branching on the shape and contents of structured data. It can make parsers, command handlers and event routers clearer than a long chain of type checks, but only when each case expresses a real pattern.
What you will learn
- Choose between
matchandif/elif. - Use literal, OR, sequence, mapping and class patterns.
- Add guards without hiding business rules.
- Avoid capture-pattern and ordering mistakes.
What Python match-case does
A match statement evaluates one subject, tries cases from top to bottom and runs the first case whose pattern and optional guard succeed. The underscore pattern is commonly used as the final catch-all. Unlike a simple switch statement, structural pattern matching can unpack sequences, read selected mapping keys and match class attributes.
Use it when one value can arrive in several recognizable shapes. Examples include commands, API events, parsed records and workflow states. For ordinary numeric ranges or unrelated Boolean conditions, if/elif often remains easier to read. Review the broader Python control structures guide before treating match as a replacement for every conditional.
Start with literal and OR patterns
def access_message(role: str) -> str:
match role.lower():
case "admin":
return "Full access"
case "editor" | "reviewer":
return "Content access"
case "student":
return "Learning access"
case _:
return "Unknown role"
The OR pattern keeps alternatives that have the same outcome together. Put specific cases first and the wildcard last. A wildcard placed early would match everything and make later cases unreachable.
Unpack sequence patterns
Sequence patterns are useful for tokenized commands. The pattern can require a fixed length or capture remaining values with a starred name.
def run_command(parts: list[str]) -> str:
match parts:
case ["add", name, score]:
return f"Add {name} with score {score}"
case ["remove", name]:
return f"Remove {name}"
case ["report", *subjects] if subjects:
return f"Report for {', '.join(subjects)}"
case _:
return "Invalid command"
This style works well after input has been split and normalized. It should not replace validation: the captured score is still text and must be converted safely before calculation.
Match dictionaries from APIs
Mapping patterns let you require only the keys needed by a branch. Extra keys are allowed unless your logic explicitly handles them.
def route_event(event: dict) -> str:
match event:
case {"type": "payment", "amount": amount} if amount > 0:
return f"Process payment: {amount}"
case {"type": "refund", "order_id": order_id}:
return f"Review refund for {order_id}"
case {"type": event_type}:
return f"Unsupported event: {event_type}"
case _:
return "Malformed event"
Real API clients also need timeouts, status checks and schema validation. The later Python API pagination and retries guide shows the network side of that workflow.
Use guards for extra conditions
A guard is an if expression attached to a case. The pattern must match before the guard runs. Guards are useful for small constraints such as a positive amount or an allowed status. If a guard contains several database calls or complex calculations, move that logic into a named function so the branch remains understandable.
Class patterns for domain objects
from dataclasses import dataclass
@dataclass
class Order:
status: str
total: float
def next_action(order: Order) -> str:
match order:
case Order(status="paid", total=total) if total >= 5000:
return "priority dispatch"
case Order(status="paid"):
return "standard dispatch"
case Order(status="cancelled"):
return "stop fulfilment"
case _:
return "manual review"
Class patterns are most valuable when the objects already represent meaningful domain concepts. If classes and objects are new, first study Python OOP with practical examples.
Common match-case mistakes
- Using a bare name as a constant: a bare name usually captures a value. Use literals or qualified enum members for constants.
- Putting a catch-all too early: cases are checked in order.
- Skipping validation: matching a shape does not prove that every captured value has the correct business meaning.
- Forcing simple conditions into patterns: an ordinary
ifmay communicate the rule better. - Ignoring the Python version: structural pattern matching requires Python 3.10 or later.
Practice exercise: order event router
Create a function that receives a dictionary for order creation, payment, cancellation or refund. Use mapping patterns to capture the required identifiers, a guard to reject non-positive amounts and a final case for malformed input. Write at least one test for every branch. When invalid events deserve distinct messages, connect the router to the Python custom exceptions guide.
When match-case is the right choice
Choose match when the alternatives describe shapes: different command layouts, event schemas or domain objects. Choose if/elif when the alternatives are mainly calculations, ranges or independent Boolean expressions. The best control structure is the one a teammate can verify quickly.
Python match-case FAQs
Which Python version supports match-case?
Structural pattern matching was introduced in Python 3.10. Confirm the runtime version before using it in a project or deployment environment.
Does match-case replace dictionaries of functions?
No. A dispatch dictionary is often ideal for a simple command-to-function mapping. Match-case becomes stronger when input has several shapes or needs unpacking and guards.
Can a case continue into the next case?
No. Python does not use switch-style fall-through. The first successful pattern and guard runs, and the match statement then ends.
Official reference: Python language reference for the match statement.
Learn Python with guided practice in Visakhapatnam
These concepts become useful when you apply them in exercises, assignments and reviewed projects. Explore Python training in Vizag for the complete curriculum, classroom and online learning options, and current batch details.
Python module learning path
Continue through the related practical guides in this course-module series: