Skip to content

Instantly share code, notes, and snippets.

@jcrist
Created September 22, 2017 16:50
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 jcrist/c382f9da34138985092707adf0d782c3 to your computer and use it in GitHub Desktop.
Save jcrist/c382f9da34138985092707adf0d782c3 to your computer and use it in GitHub Desktop.
switch-case
_cache = {}
def case(x):
if x not in _cache:
_cache[x] = type("Case", (Exception,), {})
return _cache[x]
def switch(x):
raise case(x)
def binop(op, left, right):
try: switch(op)
except case("+"):
return left + right
except case("-"):
return left - right
except case("*"):
return left * right
except case("/"):
return left / right
except: # default
raise ValueError("Unknown op %s" % op)
# In [1]: binop("*", 5, 6)
# Out[1]: 30
# In [2]: binop("/", 5, 6)
# Out[2]: 0.8333333333333334
# In [3]: binop("+", 5, 6)
# Out[3]: 11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment