Skip to content

Instantly share code, notes, and snippets.

@orez-
Last active July 15, 2019 13:53
Show Gist options
  • Save orez-/c8bdfb0563ffe44c7e42 to your computer and use it in GitHub Desktop.
Save orez-/c8bdfb0563ffe44c7e42 to your computer and use it in GitHub Desktop.
Python Switch (inspired by http://code.activestate.com/recipes/410692/ )
def switch(item):
two = Default()
one = Case(item, two)
return (one, two)
class Case(object):
def __init__(self, item, default):
self.default = default
self.skip = False
self.item = item
self.fallthrough = False
def __call__(self, *items):
if self.item in items:
self.default.skip = True
self.fallthrough = True
return self.fallthrough
class Default(object):
def __init__(self):
self.skip = False
self.fallthrough = False
def __call__(self, *items):
if self.skip:
return False
if not items:
self.fallthrough = True
return self.fallthrough
for case in switch(8):
if case(3):
print "three"
if case(4):
print "four"
break
if case():
print "default"
if case(5):
print "five"
if case(6):
print "six"
break
if case(7):
print "No!"
Break = type("Break", (Exception, ), {})()
class switch(object):
def __init__(self, item):
self.item = item
self.fallthrough = False
def __call__(self, *items):
if self.item in items or not items:
self.fallthrough = True
return self.fallthrough
def __enter__(self):
return self
def __exit__(self, etype, _, __):
return etype != Break
with switch(5) as case:
if case(3):
print "ohno!"
if case(4):
print "really no!"
raise Break
if case(5):
print "hey!"
if case(6):
print "You!"
raise Break
if case(7):
print "No!"
@beck
Copy link

beck commented Jul 15, 2019

But why?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment