Skip to content

Instantly share code, notes, and snippets.

@textbook

textbook/switch_case.py

Last active Aug 29, 2015
Embed
What would you like to do?
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