February 11, 2008

Python Switch Statements - part 2

Drew Stephens @ 3:22 pm — Tags: ,

My friend Lex read my post on Python’s lack of switch statements and sent me a note that the normal method for implementing something along the lines of a switch in Python is to use a dictionary. First, let’s define some functions:

def fooFunc():
    print 'Got foo?'
def barFunc():
    print 'Not foo.'
def nomatch():
    print 'No function to speak of!'
 
string = 'foo'

Now we can create a dictionary and just lookup the variable you want to switch upon:

# Make a dictionary and call it switch
switch = {
    'foo': fooFunc,
    'bar': barFunc
    }
 
# Find the string in the dictionary, thereby calling the function
switch[string]()
switch['bar']()
 
# Another way to do the dictionary lookup
switch.get( string, nomatch )()
switch.get( 'bar', nomatch )()

Or create an anonymous dictionary and do it all at once, more like a traditional switch:

{ 'foo' : fooFunc,
'bar' : barFunc }[string]()

Powered by WordPress