switch.py - src - atrocities - clsr.net

default = type('default', (Exception,), {})

_cases = {}
def case(*vs):
    cs = tuple(_cases[v] if v in _cases else _cases.setdefault(v, type('case %r' % v, (default,), {})) for v in vs)
    return cs[0] if len(cs) == 1 else cs

def switch(v):
    raise case(v)


# examples:
if __name__ == '__main__':
    try: switch(2)
    except case(1):
        print('one')
    except case(2):
        print('two')
    except case(3):
        print('three')
    # prints 'two'

    try: switch('good morning')
    except case('hello', 'hi'): # multiple values can be used in one case, it will match if any of them match
        print('hello there!')
    except (case('bye'), case('goodbye')): # alternatively, just use a tuple of cases
        print('goodbye!')
    except default: # catches all missed switch values; if missing, switching on missed value will produce an exception
        print('what?')
    # prints 'what?'

    try: int('qwe') # won't get caught by any of the cases
    except case(123):
        pass
    except case('qwe'):
        pass
    except default:
        pass
    # raises a ValueError