Skip to content

Instantly share code, notes, and snippets.

@panzi
Created February 10, 2014 21:23
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 panzi/8924450 to your computer and use it in GitHub Desktop.
Save panzi/8924450 to your computer and use it in GitHub Desktop.
Simple switch-case like thing for Python. I don't recommend using this or anything similar. This is just an exercise.
#!/usr/bin/env python
import re
from switch import switch
case = switch("Foo")
if case("bar"): # False
print repr("bar")
if case(re.compile("fo+",re.I)): # True
print 're.compile("fo+",re.I)'
if case(unicode,str): # True
print (unicode,str)
if case("x","y","Foo"): # True
print ("x","y","Foo")
if case(): # False
print "is never executed"
case = switch(12)
if case("12"): # Flase
print repr("12")
if case(re.compile("12")): # True
print 're.compile("12")'
import re
RegexpType = type(re.compile(''))
def switch(value):
def case(*patterns):
for pattern in patterns:
if isinstance(pattern, RegexpType):
if pattern.match(unicode(value)):
return True
elif isinstance(pattern, type):
if isinstance(value, pattern):
return True
else:
if pattern == value:
return True
return False
return case
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment