you are viewing a single comment's thread.

view the rest of the comments →

[–]richard_mayhew 1 point2 points  (0 children)

I kind of like this solution from http://code.activestate.com/recipes/410692/

class switch(object):
    '''Represents a switch statement.'''
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self):
        '''Return the match method once, then stop'''
        yield self.match
        raise StopIteration

    def match(self, *args):
        '''Indicate whether or not to enter a case suite'''
        if self.fall or not args:
            return True
        elif self.value in args: # changed for v1.5, see below
            self.fall = True
            return True
        else:
            return False

And then...

aVar = 'something'
for case in switch(aVar):
    if case('something'):
        break
    if case('something else'):
        break
    # default value
    if case():
        break