Created
June 1, 2022 08:04
-
-
Save tekknolagi/9e4bda8dbc43cde723ff58438484376b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# 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