On this page

Structural Pattern Matching in Python: A Functional Programming Tool

Published on July 3, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Structural pattern matching, introduced in Python 3.10, represents a significant step toward making Python a more expressive language for functional programming. Where traditional conditional logic requires you to manually inspect and extract data from complex structures, pattern matching allows you to declare what you expect the data to look like and have the language handle the extraction for you. This declarative approach aligns perfectly with functional programming principles: you describe what you want to match rather than how to check it, you avoid mutable state, and you write code that is both more readable and more robust. Pattern matching is not merely a switch statement — it is a powerful tool for destructuring sequences, dictionaries, and objects, binding variables to matched components, and expressing complex branching logic in a clean, functional style. This lesson teaches you how to harness structural pattern matching in Python, from basic literal matching to advanced guards, unions, and class patterns, all within the context of writing pure, declarative functional code.


From Imperative Checks to Declarative Matching​

In imperative programming, handling a value that can take multiple forms typically involves a chain of if/elif/else statements. Each condition checks something about the value — its type, its value, or the presence of certain attributes — and the body of each branch performs the appropriate action. This approach works, but it has significant drawbacks as the logic grows.

Consider a function that processes a user command. In imperative style:


def process_command_imperative(command):

    if command == "help":

        return "Available commands: help, version, exit"

    elif command == "version":

        return "v1.0.0"

    elif command == "exit":

        return "Goodbye!"

    else:

        return f"Unknown command: {command}"

This is readable for three cases. But as the number of cases grows, the function becomes a wall of conditions where the actual logic is buried under repetitive comparisons. Deep if-elif chains are prone to subtle bugs — a misplaced condition, a forgotten case, or an accidental fall‑through that silently passes the wrong data downstream.

Structural pattern matching offers a cleaner alternative:


def process_command_match(command):

    match command:

        case "help":

            return "Available commands: help, version, exit"

        case "version":

            return "v1.0.0"

        case "exit":

            return "Goodbye!"

        case _:

            return f"Unknown command: {command}"

The structure is flat and declarative. Each case declares the pattern to match, and the matching pattern's block executes. The underscore _ serves as a wildcard that matches anything — the functional equivalent of a default case.

But literal value matching is only the beginning. The real power of pattern matching lies in its ability to inspect and destructure complex data.


Understanding Structural Pattern Matching​

Structural pattern matching, often shortened to pattern matching, can be thought of as a form of syntactic sugar built on top of existing language constructs, including conditional statements and tuple unpacking. While you can live without pattern matching, it gives you new superpowers, making code more elegant, concise, and readable in a declarative style.

The match statement evaluates a subject — any Python expression — and compares the resulting value against one or more patterns listed in case clauses. When a pattern matches, the corresponding code block executes. Patterns are evaluated top to bottom, and only the first matching pattern executes — there is no fall‑through behaviour.

A pattern can do two things:

  1. Verify structure — Confirm that the subject has the expected shape.
  2. Bind variables — Capture component elements of the subject into named variables.

This combination of structure verification and variable binding is what makes pattern matching so powerful for functional programming. It allows you to write code that simultaneously checks what data looks like and extracts the parts you need — all in a single, declarative construct.


Pattern Types in Python​

Python's structural pattern matching supports a rich set of pattern types, each designed for a specific kind of data.

Literal Patterns​

Literal patterns match exact values. They work with integers, strings, booleans, and None:


def describe_value(value):

    match value:

        case True:

            return "Boolean true"

        case False:

            return "Boolean false"

        case None:

            return "None value"

        case "":

            return "Empty string"

        case 0:

            return "Zero"

        case _:

            return f"Other: {value}"

Note that True, False, and None are matched by identity (like is), not by equality. This means match 1 will not match case True, even though 1 == True is True in Python.

Or‑Patterns​

Use the pipe operator | to match any of several patterns in a single case:


def classify_day(day):

    match day.lower():

        case "monday" | "tuesday" | "wednesday" | "thursday" | "friday":

            return "Weekday"

        case "saturday" | "sunday":

            return "Weekend"

        case _:

            return "Invalid day"

Sequence Patterns​

Sequence patterns match against any sequence — lists, tuples, or any other object that implements the sequence protocol. They allow you to destructure sequences by position:


def process_command(command):

    match command.split():

        case [action]:

            # Single word command

            return f"Processing single action: {action}"

        case [action, obj]:

            # Two word command

            return f"Processing {action} on {obj}"

        case [action, obj, *rest]:

            # Three or more words

            return f"Processing {action} on {obj} with extras: {rest}"

        case _:

            return "Invalid command format"

The [action, obj] pattern matches any sequence of exactly two elements and binds action to the first and obj to the second. The *rest syntax captures any remaining elements, similar to extended unpacking in assignments.

Mapping Patterns​

Mapping patterns match against dictionaries. Unlike sequence patterns, extra keys in the subject are ignored — the pattern only requires that the specified keys exist:


def process_config(config):

    match config:

        case {"type": "server", "port": port}:

            return f"Server configured on port {port}"

        case {"type": "client", "host": host}:

            return f"Client connecting to {host}"

        case {"type": "cache"}:

            return "Cache configuration"

        case _:

            return "Unknown configuration type"

In this example, {"type": "server", "port": port} matches any dictionary that has a "type" key with value "server" and a "port" key of any value, which is then bound to the variable port.

Class Patterns​

Class patterns allow you to match against instances of specific classes and extract their attributes:


class Point:

    def __init__(self, x, y):

        self.x = x

        self.y = y



def describe_point(point):

    match point:

        case Point(x=0, y=0):

            return "Origin"

        case Point(x=0, y=y):

            return f"On Y-axis at y={y}"

        case Point(x=x, y=0):

            return f"On X-axis at x={x}"

        case Point(x=x, y=y):

            return f"Point at ({x}, {y})"

        case _:

            return "Not a point"

Class patterns require that the subject is an instance of the specified class and that the attribute values match the provided patterns.

Capture Patterns and the Wildcard​

A capture pattern is simply a name that matches anything and binds the matched value to that name. This allows you to extract values from a pattern:


match point:

    case Point(x=x, y=y):  # Captures x and y

        return f"Point at ({x}, {y})"

The wildcard pattern _ also matches anything but does not bind a value. It is typically used as a catch‑all at the end of a match statement:


case _:

    return "No match found"

Guards: Adding Conditions to Patterns​

Patterns can be combined with guards — additional conditions that must be true for a pattern to match. Guards are written after the pattern, prefixed by if:


def classify_number(n):

    match n:

        case 0:

            return "Zero"

        case n if n % 2 == 0:

            return f"Even: {n}"

        case n if n % 2 == 1:

            return f"Odd: {n}"

        case _:

            return "Not a number"

Guards allow you to express more complex matching logic while keeping the pattern itself clean. They are evaluated only after the pattern structure matches, and variables bound in the pattern are available in the guard expression.


Pattern Matching in Functional Programming​

Structural pattern matching aligns naturally with functional programming principles.

Declarative style: Pattern matching allows you to declare what you expect data to look like, rather than writing procedural checks. This shift from imperative to declarative is a cornerstone of functional programming.

Immutability: Pattern matching works best with immutable data. When you match against tuples, lists, and dictionaries without mutating them, you maintain the functional principle of avoiding side effects.

Purity: A well‑written match statement can be pure — it evaluates the subject, matches patterns, and returns a result without modifying any external state.

Referential transparency: Pattern matching expressions that return values preserve referential transparency. You can replace a match expression with its result without changing the program's behaviour.

Example: A Pure Function with Pattern Matching​


from functools import singledispatch



def parse_command(command):

    """Pure function that parses a command string."""

    match command.split():

        case ["look"]:

            return "You see a dark forest."

        case ["go", direction]:

            return f"You go {direction}."

        case ["take", item]:

            return f"You take the {item}."

        case ["quit"]:

            return "Goodbye!"

        case _:

            return f"I don't understand '{command}'."

This function is pure: it always returns the same output for the same input, has no side effects, and does not modify any external state. The pattern matching makes the code declarative and readable.


Pattern Matching vs. Traditional Functional Tools​

Pattern matching complements existing functional tools like map, filter, and reduce. Where map transforms every element of a sequence and filter selects elements based on a predicate, pattern matching is about conditional branching based on the structure of a single value.

Consider processing a list of mixed‑type values:


def process_sequence(items):

    for item in items:

        match item:

            case int(n):

                print(f"Integer: {n}")

            case str(s):

                print(f"String: {s}")

            case [first, *rest]:

                print(f"List starting with {first}, length {len(rest) + 1}")

            case _:

                print("Unknown type")

This combines iteration (a functional pattern when using map or comprehensions) with structural matching to handle heterogeneous data cleanly.


Common Pitfalls and How to Avoid Them​

1. Forgetting the Wildcard Case​

Without a wildcard case _:, a match statement does nothing if no pattern matches. This can lead to silent failures:


match value:

    case 1:

        print("One")

    # No wildcard — value 2 does nothing

Always include a wildcard case unless you are absolutely certain all possible values are covered.

2. Overusing Literal Matching​

Pattern matching is most powerful when used with sequences, mappings, and classes. Using it only for literal value matching is often no better than an if-elif chain. Leverage the structural capabilities.

3. Misunderstanding Variable Binding​

In a pattern, a name always binds a value. This can cause unexpected behaviour if you intend to compare against an existing variable:


target = 42

match value:

    case target:  # This binds value to target, not compares!

        print(f"Matched: {target}")

To compare against an existing variable, use a guard:


target = 42

match value:

    case _ if value == target:

        print("Match")

4. Assuming Fall‑Through​

Unlike switch statements in some languages, Python's match does not fall through. Only the first matching case executes. This is a feature, not a bug — it eliminates a common source of errors.

5. Using Pattern Matching for Everything​

Pattern matching is a powerful tool, but it is not always the right tool. Simple if statements are often clearer for straightforward comparisons. Use pattern matching when it genuinely improves readability, not just for the sake of using a new feature.


Summary​

Structural pattern matching, introduced in Python 3.10, is a powerful addition to the language that aligns closely with functional programming principles. It allows you to write declarative, readable code that inspects and destructures data in a single construct. This lesson has covered:

Pattern matching is not merely a switch statement — it is a sophisticated tool for expressing conditional logic in a functional, declarative style. When used appropriately, it makes Python code cleaner, more maintainable, and more expressive.


Practical Exercise​

To reinforce these concepts, try writing a pure function that processes a simplified expression language using pattern matching. Define a function evaluate(expr) that handles:

This exercise will give you practical experience with sequence patterns, recursion, and pure functions — all core concepts in functional programming.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Recursion

Next

Immutability