Another way, which is very readable and elegant, but far less efficient than a if/else structure, is to build a class such as follows, that will read and store the value to compare with, expose itself within the context as a callable that will return true if it matches the stored value:
class Switch:
def __init__(self, value):
self._val = value
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
return False # Allows traceback to occur
def __call__(self, cond, *mconds):
return self._val in (cond,)+mconds
then defining the cases is almost a match to the real switch
/case
construct (exposed within a function below, to make it easier to show off):
def run_switch(value):
with Switch(value) as case:
if case(1):
return 'one'
if case(2):
return 'two'
if case(3):
return 'the answer to the question about life, the universe and everything'
# default
raise Exception('Not a case!')
So the execution would be:
>>> run_switch(1)
one
>>> run_switch(2)
two
>>> run_switch(3)
…
Exception: Not a case!
>>> run_switch(42)
the answer to the question about life, the universe and everything
Nota Bene: