[Python-ideas] ML Style Pattern Matching for Python

Bruce Leban bruce at leapyear.org
Sat Dec 18 22:26:05 CET 2010

On 12/17/2010 6:21 PM, Eike Welk wrote:
>> After learning a bit of Ocaml I started to like its pattern matching
>> features.
>> Since then I want to have a "match" statement in Python. I wonder if
>> anybody
>> else would like this too.
 On Fri, Dec 17, 2010 at 4:14 PM, Terry Reedy <tjreedy at udel.edu> wrote:

> 1. completely redundant with respect to current Python syntax;
> 2. look like chicken scratches;
> 3. limited by the chars availables to just a few of the infinity of tests
> one might want to run.
> 4. gives special prominence to tuples, which is hardly appropriate to list
> or iterable-oriented code.
I'm skeptical that anything is worth adding here, but here's an alternative.
I'm only looking at the decomposition part. I'm using a matches keyword and
"&" and "*". (The choice here doesn't matter but I have to use something for
the examples, so please don't pick on that aspect.)

x = (3, 4)
if x matches (&a, &b):
  print(a, b)

is equivalent to

x = (3, 4)
if isinstance(x, tuple) and len(x) == 2:
  a, b = x
  print(a, b)

Or a bit more complicated:

x = [3, 4]
if x matches [3, &b, *]:

is equivalent to

x = [3, 4]
if isinstance(x, list) and x[0] == 3:
  _, b, *_ = x


if x matches {j : &k}:


if isinstance(x, dict) and j in x and len(x) == 1:
  k = a[j]

Here's a more complex example:

x matches {
  'account': (&username, &domain),
  'type': 'administrator',
  'password': &hash,
  'friends': (&best_friend, *&other_friends),

Whether or not this is useful at all is a big question, but I think it's at
least more interesting. This isn't perfect. For example

x matches Foo(a=&alpha, b=&beta)

could mean checking x.hasattr('a') but there's no guarantee that Foo(a=1,
b=2) will produce that result. Maybe that's OK.

Also, any values on the right hand side not marked by & are matched for
equality, so you could write

x matches (3 * 14 + big_complicated_expression, &y)

which is pretty ugly. And that suggests:

x matches (f(&y), g(&z))

which either doesn't make sense or is messy. We could add a __matches__
attribute to functions so they could support this, but now this is getting
pretty complicated for unclear benefit.

--- Bruce
Latest blog post: http://www.vroospeak.com/2010/11/enduring-joe-barton.html
Learn about security: http://j.mp/gruyere-security
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20101218/181a57b7/attachment.html>

More information about the Python-ideas mailing list