Skip to content

Instantly share code, notes, and snippets.

@serhii73
Created July 13, 2019 19:53
Show Gist options
  • Save serhii73/9ecfc15195f9f734d23277d47645b480 to your computer and use it in GitHub Desktop.
Save serhii73/9ecfc15195f9f734d23277d47645b480 to your computer and use it in GitHub Desktop.
Dicts can be used to emulate switch/case statements
def dispatch_if(operator, x, y):
if operator == 'add':
return x + y
elif operator == 'sub':
return x - y
elif operator == 'mul':
return x * y
elif operator == 'div':
return x / y
else:
return None
def dispatch_dict(operator, x, y):
return {
'add': lambda: x + y,
'sub': lambda: x - y,
'mul': lambda: x * y,
'div': lambda: x / y,
}.get(operator, lambda: None)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment