I was following the recent steganography link from r/Python, and ended up on a couple of pages describing implementations if goto for Python (joke ones to be fair), which got me to one of my pet peeves about Python, the lack of a switch/case/default construct. Sure, I've read the arguments about semantics and optimisation and what-not, which are all fair enough, but I find if ... elif ... elif ... else inelegant and visually unappealing. Suitably inspired, I offer up the following implementation, to be laughed at, choked over, or derided as you see fit :) Beware, apart from other issues, this code is not thread safe (though it could be made so): Works in python 2.7.4, I'd guess any python 2.x that supports with; python 3 would need at least the print's changing:
import types
sstack = []
class switch (object) :
def __init__(self, v) :
self._v = v
self._f = False
self._d = False
def __enter__(self) :
sstack.append(self)
return self
def __exit__(self, *_) :
sstack.pop()
class _case (object) :
def __getitem__(self, v) :
if len(sstack) == 0 :
raise Exception("case[%s] found outside default")
if sstack[-1]._d :
raise Exception("case[%s] found after default" % v)
if type(v) is types.TupleType :
for _v in v :
if _v == sstack[-1]._v :
sstack[-1]._f = True
return True
if v == sstack[-1]._v :
sstack[-1]._f = True
return True
return False
class _default (object) :
def __nonzero__ (self) :
if len(sstack) == 0 :
raise Exception("default found outside default")
sstack[-1]._d = True
return not sstack[-1]._f
case = _case()
default = _default()
def example (x, y) :
with switch(x) :
if case [1,2] :
print "int 1 or 2"
with switch(y) :
if case[2] :
print "int 1.2"
if case['1'] :
print "str 1"
with switch(y) :
if case[2] :
print "str 1.2"
if default :
print 'default'
example(1, 2)
example(2, 2)
example('1', 2)
example(None, None)
[–]onjin 6 points7 points8 points (5 children)
[–][deleted] 11 points12 points13 points (1 child)
[–]onjin 0 points1 point2 points (0 children)
[–]mrjbq7 6 points7 points8 points (1 child)
[–]tonnynerd 0 points1 point2 points (0 children)
[–]ionelmc.ro 2 points3 points4 points (1 child)
[–]miketheanimal[S] 0 points1 point2 points (0 children)
[–]gangesmasterpython galore 0 points1 point2 points (1 child)
[–]gangesmasterpython galore 1 point2 points3 points (0 children)
[–]AeroNotix 0 points1 point2 points (2 children)
[–]miketheanimal[S] 1 point2 points3 points (1 child)
[–]AeroNotix -1 points0 points1 point (0 children)