Last active
December 21, 2015 19:19
-
-
Save tabdulradi/6353416 to your computer and use it in GitHub Desktop.
Python Using a dict instead of Switch statements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def switch(cases, case, default_case, *args, **kwargs): | |
return cases.get(case, default_case)(*args, **kwargs) | |
def power(x): | |
return x ** 2 | |
def add(x, y): | |
return x + y | |
def illegal_operator(*args, **kwargs): | |
raise NotImplementedError("args=%s kwargs=%s" % (args, kwargs)) | |
calculator = { | |
"power": power, | |
"add": add | |
} | |
def calculate(operator, *operands): | |
return switch(calculator, operator, illegal_operator, *operands) | |
calculate("power", 2) # 4 | |
calculate("add", 2, 3) # 5 | |
calculate("weird", 2, 3) # NotImplementedError: args=(2, 3) kwargs={} | |
calculate("power", 2, 3) # TypeError: power() takes exactly 1 argument (2 given) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is a sample to show that Python developers can live without Switch statement | |
def handle_case1(): | |
print("Case 1") | |
def handle_case2(): | |
print("Case 2") | |
def handle_case3(): | |
print("Case 3") | |
def handle_default(*args, **kwargs): | |
print("No case matched, but received %s" % args) | |
cases = { | |
"case1": handle_case1, | |
"case2": handle_case2, | |
"case3": handle_case3, | |
} | |
def switch(case, *args, **kwargs): | |
cases.get(case, handle_default)(*args, **kwargs) | |
switch("case1") | |
switch("case4", "test") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment