[Python-ideas] ML Style Pattern Matching for Python

Steven D'Aprano steve at pearwood.info
Sat Dec 18 02:35:30 CET 2010


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.


I've heard of pattern matching in other languages, but never had the 
opportunity to play around with them. It seems to me though, that it's 
just an enhanced case or switch statement. Python already has had a 
proposal to add a case/switch to the language. Unfortunately, due to 
lack of consensus on functionality and syntax, and lack of any pressing 
need, it hasn't gone anywhere.


> ML style pattern matching is syntactic sugar, that combines "if" statements 
> with tuple unpacking, access to object attributes, and assignments. It is a 
> compact, yet very readable syntax for algorithms, that would otherwise require 
> nested "if" statements. It is especially useful for writing interpreters, and 
> processing complex trees.

It doesn't seem very readable to me. It looks like it is heavy on 
"magic" characters... for example, what is the purpose of the leading | 
character and the trailing -> digraph in this, and how does (| |) imply 
attribute access given the rest of Python's syntax?

      match x with
      | {| a, b |} ->             # Attribute existence and access
          print("x is an object with attributes 'a' and 'b'.")
          print("a=%s, b=%s" % (a, b))


It would require a new keyword "match", and overloading an existing 
keyword "with" to have a second meaning. Python is *very* resistant to 
adding new keywords. You would need to demonstrate that pattern matching 
leads to significant benefits over if...elif...else in order to 
compensate for the pain you cause to those who use "match" as a variable 
name. This includes Python's own standard library, which has match 
functions and methods in the re module.

It also uses special characters in a way that looks more like Perl than 
Python. With few exceptions -- iterable slicing comes to mind -- Python 
tends to avoid magic characters like that.

If you are serious about pursuing this idea, I suggest you need to 
demonstrate some non-trivial gains from pattern matching. Perhaps you 
should also look at how Haskell does it, and how functions in Haskell 
can be written concisely. Here's a toy example:

factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)


I'm interested in pattern matching, but I think the suggested syntax is 
completely inappropriate for Python. I think that for this to have any 
hope, its best bet would be as an enhancement of the case/switch PEP, 
and it would need to look like Python code, not like Haskell or OCAML.



-- 
Steven



More information about the Python-ideas mailing list