🌐
Tutorialspoint
tutorialspoint.com › home › python › python match case statement
Python Match Case Statement
February 21, 2009 - Normally Python matches an expression against literal cases. However, it allows you to include if statement in the case clause for conditional computation of match variable. In the following example, the function argument is a list of amount and duration, and the intereset is to be calculated for amount less than or more than 10000.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-match-case-statement
Python Match Case Statement - GeeksforGeeks
December 11, 2025 - The second case matches if the list has exactly three elements, binding them to x, y and z. If the list does not match either pattern, the wildcard _ is used to print "Unknown data format". A mapping is another common data type in Python and match-case can be used to match against dictionaries, checking for specific keys and values.
🌐
Python
peps.python.org › pep-0622
PEP 622 – Structural Pattern Matching | peps.python.org
For example, if a name was defined ... defined in the global scope (and # not shadowed locally). "side" must be local. match entree[-1]: case spam: ... # Compares entree[-1] == spam. case side: ... # Assigns side = entree...
🌐
Readthedocs
pc-python.readthedocs.io › en › latest › python_advanced › match_case.html
6. Match - Case — PC-Python
match subject: case <pattern_1>: <action_1> case <pattern_2>: <action_2> The example, above, of an if-elif block rewritten as a match-case block is below..
🌐
W3Schools
w3schools.com › python › python_match.asp
Python Match
month = 5 day = 4 match day: case 1 | 2 | 3 | 4 | 5 if month == 4: print("A weekday in April") case 1 | 2 | 3 | 4 | 5 if month == 5: print("A weekday in May") case _: print("No match") Try it Yourself » ... If you want to use W3Schools services ...
🌐
Python.org
discuss.python.org › ideas
Feature Suggestion - Assign match case result to a variable - Ideas - Discussions on Python.org
August 7, 2023 - Feature or enhancement Assign match-case result to a variable Pitch Currently, in Python 3.10+, match-case statements allow us to perform pattern matching and execute code blocks based on patterns. However, the result of the match-case statement cannot be directly assigned to a variable.
🌐
Plain English Westminster
benhoyt.com › writings › python-pattern-matching
Structural pattern matching in Python 3.10
At first I thought it was weird how the variables bound (and assigned) in a case block outlive the entire match block. But as shown in the above, it makes sense – you’ll often want to use the variables in the code below the match. Example from exec(), code I’m working on now.
🌐
Python Morsels
pythonmorsels.com › match-case-parsing-python
Appreciating Python's match-case by parsing Python code - Python Morsels
June 22, 2022 - That match statement is very complex, but it's much less visually dense than that if statement was. That second case statement ensures that the annotated assignment node we're matching has a value attribute which is either field(...) or dataclasses.field(...).
🌐
LearnPython.com
learnpython.com › blog › python-match-case-statement
How to Use a match case Statement in Python 3.10 | LearnPython.com
Additionally, the second case has an if statement that matches only when the optional flag --ask is in the input. Below this, you could implement code to accept user input, then delete the files if the command is confirmed. Notice we had to select all the files to delete by using a list comprehension, which is a compact way of writing a for loop. Take a look at this article for more information on for loops in Python. The third case in the above example is matched when the optional flag is not in the input command.
Find elsewhere
🌐
Gui Commits
guicommits.com › python-match-case-examples
Python Match Case Examples 🐍🕹️
September 7, 2022 - Python 3.10 has the match case which is Structural Pattern Matching. I'm going to show you what it can do with examples!
🌐
Programiz
programiz.com › python-programming › match-case
Python match…case Statement
If the status value matches any of the values in a certain case, the code within that case will execute: 200 | 201 | 202: Prints "Success" if status is 200, 201, or 202. 400 | 401 | 403: Prints "Client error" if status is 400, 401, or 403. 500 | 501 | 502: Prints "Server error" if status is ...
Top answer
1 of 5
87

If the constant you're testing against is a dotted name, then it should be treated as a constant instead of as the name of the variable to put the capture in (see PEP 636 # Matching against constants and enums):

Copyclass Codes:
    SUCCESS = 200
    NOT_FOUND = 404

def handle(retcode):
    match retcode:
        case Codes.SUCCESS:
            print('success')
        case Codes.NOT_FOUND:
            print('not found')
        case _:
            print('unknown')

Although, given how python is trying to implement pattern-matching, I think that for situations like this it's probably safer and clearer code to just use an if/elif/else tower when checking against constant values.

2 of 5
59

Hopefully I can help shed some light on why bare names work this way here.

First, as others have already noted, if you need to match values as part of your patterns, you can do so by:

  • Matching supported literals, like numbers, strings, booleans, and None
  • Matching qualified (dotted) names
  • Using additional tests in guards (which are separated from patterns by if)

I fear that we (the PEP authors) probably made a small error by including this toy snippet in an early tutorial... it's since gone a bit viral. Our goal was to lead with the simplest possible example of pattern matching, but we instead seem to have also created a confusing first impression for many (especially when repeated without context).

The most overlooked word in the title of these PEPs is "structural". If you're not matching the structure of the subject, structural pattern matching probably isn't the right tool for the job.

The design of this feature was driven by destructuring (like iterable unpacking on the LHS of assignments, but generalized for all objects), which is why we made it very easy to perform the core functionality of extracting out parts of an object and binding them to names. We also decided that it would also be useful to allow programmers to match on values, so we added those (with the condition that when the values are named, they must be qualified with a dot, in order to distinguish them from the more common extractions).

Python's pattern matching was never really designed with the intent of powering C-style switch statements like this; that's been proposed for Python (and rejected) twice before, so we chose to go in a different direction. Besides, there is already one obvious way to switch on a single value, which is simpler, shorter, and works on every version of Python: a good-ol' if/elif/else ladder!

CopySUCCESS = 200
NOT_FOUND = 404

def handle(retcode):
    if retcode == SUCCESS:
        print('success')
    elif retcode == NOT_FOUND:
        print('not found')
    else:
        print('unknown')

handle(404)

(If you're really concerned about performance or need an expression, dispatching from a dictionary is also a fine alternative.)

Top answer
1 of 1
1

In the pattern ["make", cmd], cmd is a capture pattern. Capture patterns (which look like un-dotted names such as foo, bar, or cmd) match anything, and unconditionally bind the matched value to that name.

In your example, any sequence of length 2 starting with "make" will bind the second element to cmd and execute the second case block. This is useful since it allows your app to easily determine which make command it should execute.

This happens whether cmd is already assigned or not. So, if it is already bound, that old value will be overwritten with the new, matched value.

If you want to compare a name by value instead, you have a couple of options depending on your situation:

  • If the name is dotted (like args.cmd or Class.VAR), it will automatically compare by equality (and not capture). So you can just use ["make", args.cmd] as your pattern.

  • If the name is bare (like cmd or VAR), you can use a capture pattern together with a guard to compare by equality. Using this technique, your pattern could look like ["make", c] if c == cmd. Note that since c is a capture pattern, it will be rebound just like cmd in your original example! (As you use pattern matching more, you'll find that capture patterns like c are extremely useful when performing more complex pattern matches.)

I recommend that anybody looking to familiarize themselves with Python's structural pattern matching check out the official tutorial. It covers all of the different patterns (including capture patterns) in a very easy-to-understand way.

🌐
Python
peps.python.org › pep-0636
PEP 636 – Structural Pattern Matching: Tutorial | peps.python.org
The fourth pattern captures two values, which makes it conceptually similar to the unpacking assignment (x, y) = point. If you are using classes to structure your data you can use the class name followed by an argument list resembling a constructor, but with the ability to capture attributes into variables: from dataclasses import dataclass @dataclass class Point: x: int y: int def where_is(point): match point: case Point(x=0, y=0): print("Origin") case Point(x=0, y=y): print(f"Y={y}") case Point(x=x, y=0): print(f"X={x}") case Point(): print("Somewhere else") case _: print("Not a point")
🌐
UCI
ics.uci.edu › ~pattis › ICS-33 › lectures › matchcase.txt
New in Python 10: The Match/Case (conditional) Statement
We can use a literal as the simplest kind of pattern; Python checks for a match by using == to compare the literal's value to the value of the expression. Note that the pattern _ is called a wildcard and matches anything. In the examples below, assume robot refers to an object with move, turn, and stop methods: move's arguments can be 'forward' and 'backward'; turn's arguments can be 'left' and 'right'. To start, imagine each command is one of these words. match command: case 'forward': robot.move('forward') case 'backward': robot.move('backward') case 'left': robot.turn('left') case 'right': robot.turn('right') case _ : robot.stop() # unknown command We can also replace each method call's argument by command: robot.move(command) Remember that Python examines the patterns in the case statements sequentially until if finds a match.
🌐
Medium
techytales.medium.com › pythons-switch-statement-a-beginner-s-guide-4aaffef29cb5
Python’s Alternative for Switch Statement: A Beginner’s Guide for match case statement | by Nihal Patel | Medium
June 21, 2023 - If this pattern matches, the output will be X=2, Y=3. The last case statement uses the wildcard pattern _ to catch any values that don’t match any of the previous patterns. If this pattern matches, a ValueError is raised.
🌐
Datamentor
datamentor.io › python › match-case
Python match...case Statement (With Examples)
Python also lets us use or statements in the cases. For example, number = 2 match number: case 2 | 3: print('Small') case 4 | 5 | 6: print('Medium') case 9 | 10: print('Large') # Output: Small
Top answer
1 of 2
73

Rather than match type(v), match v directly:

values = [
    1,
    "hello",
    True,
]

for v in values:
    match v:
        case str():
            print("It is a string!")
        case bool():
            print("It is a boolean!")
        case int():
            print("It is an integer!")
        case _:
            print(f"It is a {type(v)}!")

Note that I've swapped the order of bool() and int() here, so that True being an instance of int doesn't cause issues.

This is a class pattern match.

2 of 2
11

You can match directly against the type of v, but you need a value pattern to refer to the types to match, as a "dotless" name is a capture pattern that matches any value. For example,

import builtins


values = [
    1,
    "hello",
    True
]

# Caveat: this will continue to work even if someone
# rebinds the built-in, but not, for example, if builtins.str
# itself is rebound.
for v in values:
    match type(v):
        case builtins.str:
            print("It is a string!")
        case builtins.int:
            print("It is an integer!")
        case builtins.bool:
            print("It is a boolean!")
        case _:
            print(f"It is a {type(v)}!")

Note that a value pattern must be a dotted name; it's not an arbitrary expression that can evaluate to a specific value.

(Whether you really want to match against the actual type of a value, or really want to determine if a value is an instance of a given type, is another matter. In the latter case, an if-elif statement is needed.

if isinstance(v, bool):
    print("It is a boolean!")
elif isinstance(v, int):
    print("It is an int!")
elif isinstance(v, str):
    print("It is a string!")
else:
    print(f"It is a {type(v)}!")

There is no pattern that lets you use the result of calling isinstance as the case to match against. )

🌐
Mimo
mimo.org › glossary › python › match-statement
Python Match Statement: A Versatile Switch-Case in Python
... def http_status_code(status): match status: case 200: return "OK" case 404: return "Not Found" case 500: return "Server Error" case _: return "Unknown Status" The statement is also helpful for checking sequence patterns in user input. For example, you can match string patterns to ensure ...
🌐
Wrighters
wrighters.io › home › a gentle introduction to the python match statement
A Gentle Introduction to the Python Match Statement - wrighters.io
April 2, 2023 - class Constants: ONE = 1 TWO = 2 THREE = 3 match len(values): case Constants.ONE: print("One behavior") case Constants.TWO: print("Two behavior") case Constants.THREE: print("Three behavior") ... So you can use match as a switch if you really want to. But it’s much more powerful than that. Now that we’ve fumbled around a bit, instead of using match like a simple switch statement, we will match on patterns. Thinking back to our earlier examples of unpacking a list, let’s use match to do this. # change up the list so you can see we really assigning and retaining the values values = [19, 30, 1] match values: case a, b, c: print("Found 3: ", a, b, c)...