Python Language Alternatives to switch statement from other languages Use a dict of functions


Another straightforward way to go is to create a dictionary of functions:

switch = {
    1: lambda: 'one',
    2: lambda: 'two',
    42: lambda: 'the answer of life the universe and everything',

then you add a default function:

def default_case():
    raise Exception('No case found!')

and you use the dictionary's get method to get the function given the value to check and run it. If value does not exists in dictionary, then default_case is run.

>>> switch.get(1, default_case)()
>>> switch.get(2, default_case)()
>>> switch.get(3, default_case)()
Exception: No case found!
>>> switch.get(42, default_case)()
the answer of life the universe and everything

you can also make some syntactic sugar so the switch looks nicer:

def run_switch(value):
    return switch.get(value, default_case)()

>>> run_switch(1)