Last active
August 29, 2015 14:23
-
-
Save textbook/5e83044f637fda1a63fe to your computer and use it in GitHub Desktop.
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 Switch(object): | |
"""A class for faking switch syntax with a context manager. | |
Args: | |
value (object): The stored value to compare any cases to. | |
Example: | |
>>> with Switch(1) as case: | |
... if case(1): | |
... print('unity') | |
... | |
unity | |
>>> with Switch(3) as case: | |
... if case(1): | |
... print('unity') | |
... elif case(2, 3, 4): | |
... print('small') | |
... | |
small | |
>>> with Switch(5) as case: | |
... if case(1): | |
... print('unity') | |
... elif case(2, 3, 4): | |
... print('small') | |
... else: | |
... print('more than four') | |
... | |
more than four | |
""" | |
def __init__(self, value): | |
"""Create a new Switch instance.""" | |
self.value = value | |
def __call__(self, *cases): | |
"""Do any of the supplied cases match the stored value?""" | |
return any(case == self.value for case in cases) | |
def __enter__(self): | |
"""Enter the context manager.""" | |
return self | |
def __exit__(self, typ, value, traceback): | |
"""Don't do anything when leaving the context manager.""" | |
pass | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment