The following code is my solution to replace an irksome if-else block I was using. The use of a function decorator allows setting attributes (the comparision, which maybe a sequence for multiple matches) for particular methods in a class. The constructor of the switch class creates a dictionary that maps the comparision value to specific methods. Then match method can be used to retrieve the specific method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | def case(comparision):
def __assign_case(f):
f.__case = comparision
return f
return __assign_case
class switch:
def __init__(self):
self.__case_map = {}
def set_case(key,f):
self.__case_map[key] = f
a = [getattr(self,e) for e in dir(self) if getattr(self,e) is not None and hasattr(getattr(self,e),'__case')]
for f in a:
cases = getattr(f,'__case')
if isinstance(cases,tuple) or isinstance(cases,list):
for c in cases: set_case(c,f)
else:
set_case(cases,f)
def match(self,value):
return self.__case_map[value]
class b(switch):
@case((1,3))
def event_one(self):
print 'Event handler for 1,3 in b'
@case(2)
def event_two(self):
print 'Event handler for 2 in b'
a = b()
a.match(1)()
a.match(2)()
|
This code provides a cleaner alternative to do something like: if a == 1: dosomething() elif a == 2: dosomethingelse() elif a == 3: dosomethingelse2() and so on.
Please inform me if any errors are found in the implementation. I am also interested in modifications to the switch class that can generalize its use further.