[Python-ideas] Pattern Matching Syntax

Steven D'Aprano steve at pearwood.info
Fri May 4 08:11:23 EDT 2018

On Thu, May 03, 2018 at 11:36:27AM -0700, Robert Roskam wrote:

> So I started extremely generally with my syntax, but it seems like I should 
> provide a lot more examples of real use.

Yes, real-life examples will be far more compelling and useful than made 
up examples and pseudo-code.

Also, I think that you should delay talking about syntax until you have 
explained in plain English what pattern matching does, how it differs 
from a switch/case statement (in languages that have them) and why it is 
better than the two major existing idioms in Python:

- chained if...elif

- dict dispatch.

I'll make a start, and you can correct me if I get any of it wrong.

(1) Pattern matching takes a value, and compares it to a series of 
*patterns* until the first match, at which point it returns a specified 
value, skipping the rest of the patterns.

(2) Patterns typically are single values, and the match is by equality, 
although other kinds of patterns are available as well.

(3) Unlike a case/switch statement, there's no implication that the 
compiler could optimise the order of look-ups; it is purely top to 

(4) Unlike if...elif, each branch is limited to a single expression, not 
a block. That's a feature: a match expression takes an input, and 
returns a value, and typically we don't have to worry about it having 

So it is intentionally less general than a chain of if...elif blocks.

(5) We could think of it as somewhat analogous to a case/switch 
statement, a dict lookup, or if...elif, only better.

(Why is it better?)

Here is a list of patterns I would hope to support, off the top of my 

* match by equality;

* match by arbitrary predicates such as "greater than X" or 
  "between X and Y";

* match by string prefix, suffix, or substring;

* match by type (isinstance).

I think that before we start talking about syntax, we need to know what 
features we need syntax for.

There's probably more to it, because so far it doesn't look like 
anything but a restricted switch statement. Over to someone else with a 
better idea of why pattern matching has become ubiquitous in functional 


More information about the Python-ideas mailing list