Skip to content

Instantly share code, notes, and snippets.

@tekknolagi
Created June 1, 2022 08:04
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 tekknolagi/9e4bda8dbc43cde723ff58438484376b to your computer and use it in GitHub Desktop.
Save tekknolagi/9e4bda8dbc43cde723ff58438484376b to your computer and use it in GitHub Desktop.
# Copyright Andy Chu
class switch(object):
"""A ContextManager that translates to a C switch statement."""
def __init__(self, value):
# type: (int) -> None
self.value = value
def __enter__(self):
# type: () -> switch
return self
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> bool
return False # Allows a traceback to occur
def __call__(self, *cases):
# type: (*Any) -> bool
return self.value in cases
with switch(x) as case:
if case(0):
print('zero')
print('zero')
elif case(1, 2):
print('one or two')
elif case(3, 4):
print('three or four')
else:
print('default')
print('another')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment