Is there no switch function in Python

Alex Martelli aleaxit at yahoo.com
Sat Sep 11 02:13:36 EDT 2004


Leif K-Brooks <eurleif at ecritters.biz> wrote:

> Bengt Richter wrote:
> > But IWT if we had named local code suites, we could exec them safely via
a mapping. E.g.,
> > 
> >     def foo(var): # following is not legal code ;-)
> >         v1: print 'var is one'
> >         v2: # any suite should be ok, not just one-liners
> >             print 'var',
> >             print 'is two'
> >         switch = {1:v1, 2:v2}    
> >         exec switch.get(var, '')
> 
> I'm probably missing something, but what's wrong with:
> 
> def foo(var):
>       def v1(): print 'var is one'
>       def v2():
>               print 'var',
>               print 'is two'
>       switch = {1:v1, 2:v2}
>       switch.get(var, lambda:None)()

Nothing wrong.  However, if v1 and v2 needed to rebind some names within
foo, they couldn't according to def's semantics -- they could only
rebind local names of their own, or global names with a global
statement, but not local names in their outer function foo.  I think the
right approach, if that feature is a must-have, might be to add the one
missing feature, not with a weird new syntax which forces one to choose
between taking arguments and rebinding outer functions' locals, but with
an optional scope indicator on variables.  Just IMHO, anyway.


Alex



More information about the Python-list mailing list