On Saturday 11 June 2005 07:35 pm, Steven D'Aprano wrote: > On Sat, 11 Jun 2005 16:15:42 +0000, 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. > [...] > There is no case statement in Python. If you don't care about > readability, one alternative is to use a dictionary: > > case = {5: do_this, 6: do_that} > case.get(x, do_something_else)()
The really nice thing about using dictionaries for this kind of thing in Python is that what was previously hardcoded is now (dynamic) data. That makes alterations like adding a new case extremely trivial (you could load it from a config file for example, or it could be altered by plugin code which simply updates the dictionary to register itself). In my experience with C, this kind of change always comes up with switch statements, so it's nice to neatly sidestep the problem with dictionaries in Python. And perhaps that removal of a false lead is the real reason Python doesn't have a switch/case construct -- it encourages you to use a smarter solution which you'll be glad of later on. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list