Skip to content

Instantly share code, notes, and snippets.

@fomightez
Last active June 13, 2019 00:01
Show Gist options
  • Save fomightez/f282dce17d33391310ad3477e4a9c707 to your computer and use it in GitHub Desktop.
Save fomightez/f282dce17d33391310ad3477e4a9c707 to your computer and use it in GitHub Desktop.
Python to emulate switch/case statements
# I like the example at https://inventwithpython.com/blog/2019/06/05/pythonic-ways-to-use-dictionaries/ better than this one I had found earlier>
##
##
def dispatch_dict(operator, x, y):
'''
Python to emulate switch/case statements
based on https://books.google.com/books?id=C0VKDwAAQBAJ&pg=PT226&lpg=PT226&dq=%22dispatch_dict+(operator%22&source=bl&ots=Ja0bhOYv9A&sig=j7OZGsWpps97z8jHByquiYIuRBY&hl=en&sa=X&ved=2ahUKEwjW4siOl8fcAhWKTN8KHSa3ApYQ6AEwAnoECAMQAQ#v=onepage&q=%22dispatch_dict%20(operator%22&f=false
https://twitter.com/w_cazzola/status/1023917802627973126
https://gist.github.com/carlessanagustin/6d7584b963338426a3691d355fe28f55
'''
return {
'+': lambda: x + y,
'-': lambda: x - y,
'*': lambda: x * y,
'/': lambda: x / y,
}.get(operator, lambda: None)()
>>> dispatch_dict('+',21, dispatch_dict('*',3,7))
42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment