Created
February 10, 2014 21:23
-
-
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.
This file contains 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
#!/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")' |
This file contains 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
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