Is there no switch function in Python

Leif K-Brooks eurleif at
Sat Sep 11 04:20:13 CEST 2004

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)()

More information about the Python-list mailing list