Created
July 12, 2018 14:23
-
-
Save maxfischer2781/6c4952d3264a974344fb0f825343ba78 to your computer and use it in GitHub Desktop.
A class based implementation of a switch "statement" for Python
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
def switch(on): | |
def switch_decorator(cls): | |
for try_case in cls.__dict__.values(): | |
try: | |
switch_case = try_case.__switch_case__ | |
except AttributeError: | |
pass | |
else: | |
print(switch_case, '?') | |
if on == switch_case: | |
return try_case(on) | |
raise KeyError('%r not in %r' % (on, cls)) | |
return switch_decorator | |
def case(what): | |
def case_decorator(func): | |
func.__switch_case__ = what | |
return func | |
return case_decorator | |
@switch(2) | |
class Cases: | |
@case(1) | |
def bar(what): | |
print(what, '=> 1') | |
return what | |
@case(2) | |
def foo(what): | |
print(what, '=> 2') | |
return what | |
print(Cases) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment