[Python-Dev] Switch statement

Phillip J. Eby pje at telecommunity.com
Wed Jun 21 20:01:34 CEST 2006


At 10:27 AM 6/21/2006 -0700, Guido van Rossum wrote:
>On 6/21/06, Phillip J. Eby <pje at telecommunity.com> wrote:
> > At 09:55 AM 6/21/2006 -0700, Guido van Rossum wrote:
> > >BTW a switch in a class should be treated the same as a global switch.
> > >But what about a switch in a class in a function?
> >
> > Okay, now my head hurts.  :)
>
>Welcome to the club. There's a Monty Python sketch appropriate...

Aha!  So *that's* why Jim Fulton is always going "Waaaa".  :)


> > A switch in a class doesn't need to be treated the same as a global switch,
> > because locals()!=globals() in that case.
>
>But that's not the discerning rule in my mind; the rule is, how to
>define "at function definition time".

Waaaaa!  (i.e., my head hurts again :)


> > I think the top-level is the only thing that really needs a special case
> > vs. the general "error if you use a local variable in the expression" rule.
>
>To the contrary, at the top level my preferred semantics don't care
>because they don't use a hash.
>
>The strict rules about locals apply when it occurs inside a function,
>since then we eval the case expressions at function definition time,
>when the locals are undefined. This would normally be good enough, but
>I worry (a bit) about this case:
>
>   y = 12
>   def foo(x, y):
>     switch x:
>     case y: print "something"
>
>which to the untrained observer (I care about untrained readers much
>more than about untrained writers!) looks like it would print
>something if x equals y, the argument, while in fact it prints
>something if x equals 12.

I was thinking this should be rejected due to a local being in the 'case' 
expression.


> > Actually, it might be simpler just to always reject local variables -- even
> > at the top-level -- and be done with it.
>
>Can't because locals at the top-level are also globals.

But you could also just use literals, and the behavior would then be 
consistent.  But I'm neither so enamored of that solution nor so against 
if/elif behavior that I care to argue further.

One minor point, though: what happens if we generate an if/elif for the 
switch, and there's a repeated case value?  The advantage of still using 
the hash-based code at the top level is that you still get an error for 
duplicating keys.

Ugh.  It still seems like the simplest implementation is to say that the 
lookup table is built "at first use" and that the case expressions may not 
refer to variables that are known to be bound in the current scope, or 
rebound in the case of the top level.  So the 'case y' example would be a 
compile-time error, as would my silly "words" example.  But code that only 
used "constants" at the top level would work.



More information about the Python-Dev mailing list