Skip to content

Instantly share code, notes, and snippets.

@textbook
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save textbook/5e83044f637fda1a63fe to your computer and use it in GitHub Desktop.
Save textbook/5e83044f637fda1a63fe to your computer and use it in GitHub Desktop.
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