Any speed issue ?
[EMAIL PROTECTED] wrote: > Philippe C. Martin wrote: >> Leif K-Brooks wrote: >> >> > Joe Stevenson wrote: >> >> I skimmed through the docs for Python, and I did not find anything >> >> like >> >> a case or switch statement. I assume there is one and that I just >> >> missed it. Can someone please point me to the appropriate document, >> >> or >> >> post an example? I don't relish the idea especially long if-else >> >> statements. >> > >> > If you really want one, you could use >> > <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410692>. >> >> I _love_ Python! > > > Well, if you loved that, here's something even more evil. This was > Bengt Richter's original idea that Cliff Wells and I improved upon. > First define some functions and classes: > > . _cache = {} > . > . class _BaseCaseException(Exception): > . pass > . > . def switch(v): > . if v not in _cache: > . class _CaseException(_BaseCaseException): > . pass > . _cache[v] = _CaseException > . raise _cache[v] > . > . def case(v): > . if v not in _cache: > . class _CaseException(_BaseCaseException): > . pass > . _cache[v] = _CaseException > . return _cache[v] > . > . default = _BaseCaseException > > > Then you can define a switch statement like this: > > . x = 2 > . > . try: switch(x) > . > . except case(1): > . print "Case 1" > . > . except case(2): > . print "Case 2" > . > . except case(3): > . print "Case 3" > . > . except default: > . print "Default" > . > . except NameError: > . print "You can still catch regular exceptions like NameError" > > > > I-love-Python-too-but-this-isn't-why-ly yr's, > -- http://mail.python.org/mailman/listinfo/python-list