Is there no switch function in Python

Alex Martelli aleaxit at yahoo.com
Thu Sep 9 22:27:02 CEST 2004


Rudi Hansen <rsh_remove_this_ at pobox.dk> wrote:

> I dont seem to be able to find the switch statement in Python.

Right, there isn't one.

> 
> I would like to be able to do
> 
> switch(var)
>     case 1 :
>         print "var = 1"
>     case 2:
>         print "var = 2"
> 
> But it seems that i have to do.
> 
> if(var=1)
>     print "var =1"
> elseif(var=2)
>     print "var=2"
> 
> Is ther no easier way?? 

several, starting with

if var in (1,2): print 'var = %s' % var

The most Pythonic idiom, when you have to do something substantial in
each branch of the switch, is a dictionary of callables -- in this toy
case it might be:

switch = {1: lambda: sys.stdout.write('var=1\n'),
               2: lambda: sys.stdout.write('var=2\n'), }
switch.get(var, lambda: '')()

An if/elif tree is also fine, though the syntax is not as you think...:

if     var == 1:
    print 'var is one'
elif  var == 2:
    print 'var is two'



Alex



More information about the Python-list mailing list