Switch statement (was: Lambda going out of fashion)

Skip Montanaro skip at pobox.com
Thu Dec 23 11:02:09 EST 2004


    Stephen> {
    Stephen>  'one': lambda x:x.blat(),
    Stephen>  'two': lambda x:x.blah(),
    Stephen> }.get(someValue, lambda x:0)(someOtherValue)

One thing to remember is that function calls in Python are pretty damn
expensive.  If x.blat() or x.blah() are themselves only one or two lines of
code, you might find that your "switch" statement is better written as an
if/elif/else statement.  You're making potentially three function calls
(get(), lambda and x.blat() or x.blah()) to perform what might only be a
small handful of inline statements.  I'll ignore the readability cost of
your solution vs. an if statement.

    Stephen> So, the questions I am asking are: Is this okay with everyone?

Sure.  I'll adjust.

    Stephen> Does anyone else feel that lambda is useful in this kind of
    Stephen> context?

It's useful in this sort of context.  It will probably always be limited to
single expressions, which will always leave it a second-class citizen in
Python.  Interestingly enough, lambda in the Lisp world has the same
limitation, however, since Lisp code is nothing but a series of
s-expressions, that's not a problem.

    Stephen> Are there alternatives I have not considered?

I've never seen a situation where if/elif/else wasn't adequate or was less
clear than the many attempts at switch-like behavior.

Folks (in general), there is still an open PEP on a switch statement for
Python.  It's been idle since late 2001:

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

It would help if interested people were to take a look at it and identify
open issues.  If you google for pep 275 you will probably find relevant
python-dev discussions from the 2001/2002 timeframe.  Thomas Wouters' patch
for the interpreter would also need to be resurrected and brought
up-to-date.  I not longer remember why the PEP stalled.

Skip



More information about the Python-list mailing list