Python gets pattern matching

Radek Bezvoda
2 min readFeb 10, 2021

A few days ago, PEP 634 authored by Brandt Bucher and the creator of Python language Guido van Rossum was accepted. So, lets have a look at what it means for us, Pythonistas.

Photo by James Peacock on Unsplash

The simplest example may look like this (example adapted from PEP 636):

def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case _:
return "Something's wrong with the Internet"

So, it looks like we are getting a switch/case logic known from many other programming languages. This structure can for sure simplify our complicated if/elif code. What about the single underscore in the last case statement, do you ask? That matches any result, so it’s the last resort in our decision tree.

So, is it just yet another switch/case implementation? Not at all, as we can match quite a sofisticated pattern. Say our status comes sometimes as a single value and sometimes as a numeric code together with a textual representation:

def http_error(status):
match status.split():
case [numeral]: # got single element status code
print(f'Numeric code: {numeral}')
case [numeral, text]: # got two element status code here
print(f'Numeric code: {numeral}')
print(f'Text code: {text}')
case _: # other
print('Something's wrong with the Internet')

So, this is why it’s called pattern matching!

We can also match two or more patterns in one case branch using the | operator. And there are far more: It’s possible to match a particular string with any value like in the next example.

case ['404', text]: # got 404 + any text this time
print(f'Numeric code: 404')
print(f'Text code: {text}')

So, this was a quick look at pattern matching we should see in Python 3.10. For further details, see the PEP 634 proposal, and especially the excellent tutorial in PEP 636.

I’m looking forward to play with this goodie in the next Python 3 major release. What about you?

--

--