Is there no switch function in Python
Bengt Richter
bokr at oz.net
Sat Sep 11 02:15:45 EDT 2004
On Fri, 10 Sep 2004 22:20:13 -0400, 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)()
Sorry, I should have shown an example that really depends on local name space rebinding,
which the OP's example doesn't, and which was my main point. E.g., try getting the effect of:
def foo(var): # following is not legal code ;-)
v1: print 'var is one'
var += 1
status = 'incremented'
v2: # any suite should be ok, not just one-liners
print 'var',
print 'is two'
var *= 2
status = 'doubled'
switch = {1:v1, 2:v2}
exec switch.get(var, '')
print 'var is now %r, and was %s.' % (var, status)
return var, status
Regards,
Bengt Richter
More information about the Python-list
mailing list