Lambda going out of fashion
Steven Bethard
steven.bethard at gmail.com
Thu Dec 23 01:46:21 EST 2004
Stephen Thorne wrote:
>
> {
> 'one': lambda x:x.blat(),
> 'two': lambda x:x.blah(),
> }.get(someValue, lambda x:0)(someOtherValue)
>
> The alternatives to this, reletively simple pattern, which is a rough
> parallel to the 'switch' statement in C, involve creating named
> functions, and remove the code from the context it is to be called
> from (my major gripe).
Here's what my code for a very similar situation usually looks like:
py> class Foo(object):
... def blat(self):
... print "blat"
... def blah(self):
... print "blah"
...
py> key, foo = 'two', Foo()
py> try:
... result = dict(one=Foo.blat, two=Foo.blah)[key](foo)
... except KeyError:
... result = 0
...
blah
As you can see, I just use the unbound methods of the parent class
directly. Of course this means that your code won't work if 'foo' isn't
actually a Foo instance. So you lose a little generality, but you gain
a bit in conciceness of expression (IMHO). Note also that I don't use
dict.get, relying on the KeyError instead. Usually, my case for when no
function applies is complex enough to not be expressable in a lambda
anyway, so this is generally more appropriate for my code.
While I don't generally find that I need lambda, I'm not particularly
arguing against it here. I just thought it might be helpful to
demonstrate how this code might be written concicely without lambdas.
Steve
More information about the Python-list
mailing list