Skip to content

Instantly share code, notes, and snippets.

@dsvictor94
Created May 1, 2017 07:29
Show Gist options
  • Save dsvictor94/87f095437762e3f6553588975c6869eb to your computer and use it in GitHub Desktop.
Save dsvictor94/87f095437762e3f6553588975c6869eb to your computer and use it in GitHub Desktop.
python switch implementetion
class switch(object):
def __init__(self, var):
self.var = var
def __enter__(self):
self.match = False
self.stops = False
def case(v=None):
if(self.stops):
return False
if(v == self.var or v is None):
self.match = True
return self.match
def stop():
self.stops = True
return case, stop
def __exit__(self, *args):
pass
if __name__ == '__main__':
print('test switch with "break"')
with switch(10) as (case, stop):
if case(5):
print("five")
stop()
if case(10):
print("ten")
stop()
if case(20):
print("twenty")
stop()
if case():
print("other")
print('test switch without "break"')
with switch(10) as (case, stop):
if case(5):
print("five")
if case(10):
print("ten")
if case(20):
print("twenty")
if case():
print("other")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment