case/switch statement?

Skip Montanaro skip at pobox.com
Sat Jun 11 20:47:58 EDT 2005


    Steven> I've never understood why something like:

    Steven> if x = 5:
    Steven>     do_this
    Steven> elif x = 6:
    Steven>     do_that
    Steven> else:
    Steven>     do_something_else

    Steven> is supposed to be "bad", but

    Steven> case of:
    Steven>     x = 5:
    Steven>         do_this
    Steven>     x = 6:
    Steven>         do_that
    Steven> otherwise:
    Steven>         do_something_else

    Steven> is supposed to be "good".

    ...

    Steven> Arguably, a case statement *might* allow the compiler to
    Steven> optimize the code, maybe, sometimes. 

If the case values are constants known to the compiler, it can generate O(1)
code to take the correct branch.  (In fact, that could be done by the
compiler for if statements such as in your example today.  It just isn't.)
It is precisely this behavior that is desired in many situations.  See PEP
275 for details:

    http://www.python.org/peps/pep-0275.html

Skip



More information about the Python-list mailing list