Python's lack of a 'switch' statement has garnered much discussion and even a PEP. The most popular substitute uses dictionaries to map cases to functions, which requires lots of defs or lambdas. While the approach shown here may be O(n) for cases, it aims to duplicate C's original 'switch' functionality and structure with reasonable accuracy.
Python, 88 lines
While the use of 'for ... in' may not be semantically accurate here (it will only ever execute the suite once), the fact that we are trying multiple cases (even if they are all within the same iteration) at least gives it the illusion of making some sense.
For better or worse, changing the switched variable within the suite will have no effect on the proceeding cases. This is a diversion from C functionality.
As noted above, case() (with no arguments) is used in place of 'default'. Another option would be to just omit the last conditional or use 'if True:'. To make that part look even more like the classic idiom, you could: --> change "yield self.match" in __iter__ to "yield self.match, True" --> change "for case in" to "for case, default in" --> change "if case():" to "if default:"
...but, in my opinion, this slight adjustment is just a trade-off of one area of readability for another.
As far as I can tell, people generally use switch for its conciseness and readability, and not for its better lookup time, if that is indeed true.
Alan Haffner's dictionary-based recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/181064
Runsun Pan's dictionary-based recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269708
PEP 275 - Switching on Multiple Values: http://www.python.org/peps/pep-0275.html