Python match statement: how to use values stored in variables
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):
class 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.
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!
SUCCESS = 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.)
Aside from using literal values, the Value Patterns section of PEP 635 mentions the use of dotted names or the use of guards. See below for comparison:
Literal values
def handle(code):
match code:
case 200:
print('success')
case 404:
print('not found')
case _:
print('unknown')
References:
- https://www.python.org/dev/peps/pep-0635/#literal-patterns
- https://www.python.org/dev/peps/pep-0636/#matching-specific-values
Dotted names
Any dotted name (i.e. attribute access) is interpreted as a value pattern.
class StatusCodes:
OK = 200
NOT_FOUND = 404
def handle(code):
match code:
case StatusCodes.OK:
print('success')
case StatusCodes.NOT_FOUND:
print('not found')
case _:
print('unknown')
References:
- https://www.python.org/dev/peps/pep-0635/#value-patterns
- https://www.python.org/dev/peps/pep-0636/#matching-against-constants-and-enums
Guards
[A] guard is an arbitrary expression attached to a pattern and that must evaluate to a "truthy" value for the pattern to succeed.
SUCCESS = 200
NOT_FOUND = 404
def handle(code):
match code:
case status if status == SUCCESS:
print('success')
case status if status == NOT_FOUND:
print('not found')
case _:
print('unknown')
References:
- https://www.python.org/dev/peps/pep-0635/#guards
- https://www.python.org/dev/peps/pep-0636/#adding-conditions-to-patterns