[Python-ideas] Pattern matching

Devin Jeanpierre jeanpierreda at gmail.com
Wed Apr 8 18:24:05 CEST 2015


On Wed, Apr 8, 2015 at 10:07 AM, Andrew Barnert
<abarnert at yahoo.com.dmarc.invalid> wrote:
> On Apr 8, 2015, at 05:34, Anthony Towns <aj at erisian.com.au> wrote:
> Anyway, I think your additions and changes make a much better proposal than
> what I originally had, and we're now probably on track to the best Pythonic
> design for ML-style pattern matching--but I still don't think it's worth
> adding to Python, or even writing as a PEP for Guido to reject. Have you
> ever written code where you really missed the feature (except in the first
> hour back on Python after a week of Haskell hacking)? Or seen any real code
> that would be substantially improved? If not, this still just seems like a
> feature for its own sake, or more than one way to do it for no reason.

All compiling / tree handling code is really annoying without pattern patching.

Here is a fragment of code from the ast module:

elif isinstance(node, BinOp) and \
     isinstance(node.op, (Add, Sub)) and \
     isinstance(node.right, Num) and \
     isinstance(node.right.n, complex) and \
     isinstance(node.left, Num) and \
     isinstance(node.left.n, (int, long, float)):

Here is what it would look like if we were inside a match statement thingy:

# I picked the arg order out of the docs, but it's a bit too "clever"
case BinOp(Num(left), (Add | Sub), Num(right)):
    if isinstance(left, (int, long, float)) and isinstance(right, complex):
        ...

NodeVisitor etc. are hacked up pattern matching-like thingies that
mitigates this when they apply.

It's harder to demonstrate, but sre_compile is even worse -- it takes
in a tree of opcodes and argument vectors, where the argument vector
values are totally undocumented etc. (and, IIRC, sometimes they are
lists, sometimes they aren't, depending on the opcode).  If it used
some disjoint union type that unpacked nicely in a match statement,
the compiling code would be much more readable, and the internal data
structure would be easier to understand.

-- Devin


More information about the Python-ideas mailing list