[Python-ideas] Match statement brainstorm

Steven D'Aprano steve at pearwood.info
Mon May 30 14:35:17 EDT 2016


On Sat, May 28, 2016 at 02:13:33PM +1200, Greg Ewing wrote:
[...]
> Finally we could allow "case class" to be abbreviated to
> just "class":
> 
>    switch obj:
>       class Intersection(
>          class Line(class Point(?x1, ?y1), class Point(?x2, ?y2)),
>          class Line(class Point(?x3, ?y3), class Point(?x4, ?y4))):
> 
> Is that unacceptably verbose? I don't know. 

Verbose, not so much. Cryptic? Hell yes! Who is going to be able to 
guess what it means? We're no longer even in the same galaxy as 
executable pseudo-code.

Try this as an exercise: given the above, explain in plain English what 
it does and what the result will be. What exactly is being matched?

Those familiar with C-like switches are going to be totally confused. 
They'll probably wonder if you are matching "if obj == the class 
Intersection", and have no idea what's going on with the nested Line and 
Point stuff.

Those familiar with classes and the class keyword are going to wonder 
what class definitions are doing inside the class declaration. Does this 
mean we can now do this?

class Child(class Parent: pass):
    def method(self): ...

Obviously not, but that's what it looks like.

I wonder whether the real problem here is that pattern matching as a 
concept is simply too concise for mere mortals? Once you get past the 
trivial Haskell-esque:

def factorial(n):
    switch n:
        0: return 1
        n: return n*fact(n-1)

its just doing too much in too little code to be easily comprehensible.



-- 
Steve


More information about the Python-ideas mailing list