Skip to content

Instantly share code, notes, and snippets.

@uroybd
Last active November 14, 2017 09:14
Show Gist options
  • Save uroybd/5429a1038b9b78327894b98f9efc054d to your computer and use it in GitHub Desktop.
Save uroybd/5429a1038b9b78327894b98f9efc054d to your computer and use it in GitHub Desktop.
A 'Classy' Case for Python
class Case:
"""A Class to simulate case behavior in a more compact way.
Optionaly, default value and a conditional function can be passed.
cases and **kwargs are for flexibility since you can't have nothing
but string keys in kwargs. They both get combined in a single switch.
Return value for switches can be either a value or callable.
Stupid thingy, I know right! :D
"""
def __init__(self, default=None, condition=lambda x: x, cases={}, **kwargs):
self.condition = condition
self.default = default
self.switch = cases
for k, v in kwargs.items():
self.switch[k] = v
def __new__(self, default=None, condition=lambda x: x, cases={}, **kwargs):
if cases or kwargs:
return super(Case, self).__new__(self)
else:
raise ValueError
def add(self, key, val):
self.switch[key] = val
def __call__(self, val):
rval = self.switch.get(self.statement(val), self.default)
return rval(val) if callable(rval) else rval
@uroybd
Copy link
Author

uroybd commented Nov 14, 2017

An example:

>>> cases = {10: "It's Ten", 5: "It's Five"}
>>> mc = Case(condition=lambda x: x*5, default="Not Found", cases=cases, nine="It's Nine")
>>> mc(1)
"It's Five"
>>>mc(5)
'Not Found'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment