[Python-Dev] Re: switch statement

Phillip J. Eby pje at telecommunity.com
Fri Apr 22 06:25:22 CEST 2005

At 06:10 PM 04/21/2005 +0100, Michael Hudson wrote:
>But the visitor pattern is pretty grim, really.  It would be nice (tm)
>to have something like:
>   match node in:
>     Assign(lhs=Var(_), rhs=_):
>        # lhs, rhs bound in here
>     Assign(lhs=Subscr(_,_), rhs=_):
>        # ditto
>     Assign(lhs=Slice(*_), rhs=_):
>        # ditto
>     Assign(lhs=_, rhs=_):
>        raise SyntaxError
>in Lib/compiler.

FWIW, I do intend to add this sort of thing to PyProtocols' predicate 
dispatch system.  Actually, I can dispatch on rules like the above now, 
it's just that you have to spell out the cases as e.g.:

     @do_it.when("isinstance(node, Assign) and isinstance(node.lhs, Subscr)")
     def do_subscript_assign(node, ...):

I'd like to create a syntax sugar for pattern matching though, that would 
let you 1) use a less verbose way of saying the same thing, and 2) let you 
bind the intermediate values to variables that then become accessible in 
the function body as locals.

Anyway, the main holdup on this is deciding what sort of Python syntax 
abuse should represent variable bindings.  :)  Maybe something like this 
will be suitably horrific:

    @do_it.when("node in Assign.match(lhs=`lhs` in Subscr,rhs=`rhs`)")
    def do_subscript_assign((lhs,rhs), node, ...):

But I think maybe here the cure is worse than the disease.  :)  Pushed this 
far, it seems to beg for new syntax to accommodate in-expression variable 
bindings, something like 'var:=value'.  Really, though, the problem is 
probably just that inline variable binding is downright unpythonic.  The 
only time Python does anything vaguely similar is with the 'except 
type,var:' syntax.

More information about the Python-Dev mailing list