Skip to content

Instantly share code, notes, and snippets.

@tabdulradi
Last active December 21, 2015 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tabdulradi/6353416 to your computer and use it in GitHub Desktop.
Save tabdulradi/6353416 to your computer and use it in GitHub Desktop.
Python Using a dict instead of Switch statements
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 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