Skip to content

Instantly share code, notes, and snippets.

@13steinj
Created March 12, 2016 20:43
Show Gist options
  • Save 13steinj/7f6e32f7ece13f8427e2 to your computer and use it in GitHub Desktop.
Save 13steinj/7f6e32f7ece13f8427e2 to your computer and use it in GitHub Desktop.
Python switches - because im tired of plainly using dictionaries and typing all this out manually.
# if supporting Py3.0 or 3.1
# from six import callable
class switch_non_break_return_code(object):
def __init__(self, val):
self.val = val
class switch(object):
def __init__(self, default=None, **cases):
self.cases = cases
self.default = default
if not callable(default):
self.default = self.non_func_wrapper(default)
for k, v in cases.values():
if not callable(v):
self.cases[k] = self.non_func_wrapper(val)
@staticmethod
def non_func_wrapper(val):
return lambda *a, **kw: val
def call(statement, *a, **kw):
runner = self.cases.get(statement, self.default)
while True:
ret = runner(*a, **kw)
if not isinstance(ret, switch_non_break_returncode):
return ret
runner = self.cases.get(ret.val, self.default)
__call__ = call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment