Last active
November 27, 2016 15:35
-
-
Save WindfallLabs/a762e2ccee490c95b49d6491239bd0c4 to your computer and use it in GitHub Desktop.
A Python implementation of JavaScript switches
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
""" | |
swtich.py -- JS switches in Python (proof of concept) | |
Author: Garin Wally; Nov 2016 | |
Just took the JavaScript tutorial at codecademy and thought switches were | |
pretty cool, so I coded one up in Python. | |
I have to admit, this implementation is not great, not pretty, and likely | |
not shorter than a standard if/elif/else block. | |
""" | |
class Switch(object): | |
def __init__(self, cases={}): | |
self.cases = cases | |
def add_case(self, key, value): | |
self.cases[key] = value | |
def set_default(self, default): | |
self.cases['default'] = default | |
def __call__(self, case): | |
if self.cases == {}: | |
raise KeyError("No switch cases exist") | |
elif "default" not in self.cases.keys(): | |
raise KeyError("No default case set") | |
if case in self.cases.keys(): | |
if callable(self.cases[case]): | |
return self.cases[case]() | |
else: | |
return self.cases[case] | |
else: | |
if callable(self.cases['default']): | |
return self.cases['default']() | |
else: | |
return self.cases['default'] | |
# Ideally, you'd import switch and the above code would | |
# already be taken care of | |
switch = Switch() | |
# Test function | |
def _test(): | |
"""Namespaced test function.""" | |
switch = Switch() | |
# Setup cases | |
def case1(): | |
return "Switch case 1 activated" | |
def case2(): | |
return "Switch case 2 activated" | |
case3 = "Switch case 3 activated" | |
# Setup the default case | |
def default(): | |
return "Default case activated" | |
# Then add your cases to the switch | |
switch.add_case("case1", case1) | |
switch.add_case("case2", case2) | |
switch.add_case("case3", case3) | |
switch.set_default(default) | |
# Then use it | |
assert switch("case1") == "Switch case 1 activated" | |
assert switch("case3") == "Switch case 3 activated" # non-callable string | |
assert switch("not an option") == "Default case activated" | |
print("tests passed") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment