Last active
November 14, 2017 09:14
-
-
Save uroybd/5429a1038b9b78327894b98f9efc054d to your computer and use it in GitHub Desktop.
A 'Classy' Case for Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An example: