Lambda going out of fashion

Jp Calderone exarkun at divmod.com
Thu Dec 23 09:37:04 EST 2004


On Thu, 23 Dec 2004 13:36:08 GMT, rzed <jello at comics.com> wrote:
>Stephen Thorne <stephen.thorne at gmail.com> wrote in
> news:mailman.8299.1103775211.5135.python-list at python.org: 
> > [snip]
> > 
> > {
> >  '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).
> >
> > [snip]
> 
> Not addressing lambdas per se, but something similar to your pseudo-
> switch statement can be done without using them at all. One way might 
> be to use a function dictionary wrapped in an accessor function, such 
> as this:
> 
> def dofns(key):
>     fd2 = {
>     0:'print "Key 0"',
>     1:'print "one"',
>     4:"\n".join(['for ix in range(15):',
>     	    	'  print "%s%d" % (" "*ix,ix)']),
>     }
>     try:
>         exec(fd2[key])
>     except KeyError:
>         print 'Key',key,'not found'
> 

  I hate to be nasty, but *ugh* what a horrible way to start the day.

  There are so many things wrong with this.

  By exec'ing code strings you lose compile-time _syntax_ 
checking.  I'm all for dynamicism, but it really is nice to let the 
compiler do _something_ things for you.

  By exec'ing code strings you slow down the entire function 
by forcing a slower name-lookup code path in the interpreter.

  By exec'ing code strings you lose the ability to pass values 
back to your caller (oh, you could "return" in one of those, but
*ugg* that'd be even more terrible, and probably not what you want
in most cases, since it doesn't let you get at the value except from
your caller.  you could also set names in the local namespace but
that's pretty messed up too, python already has a function return
convention, making up your own is no fun).

  There are probably more reasons this is bad too.

  Even using `def' to define a function for each of these would be 
preferable.

  Aside from that, exec() isn't a function.  You "exec foo", not 
"exec(foo)".  The latter works simply because parens act as to set 
precedent instead of as part of function call syntax when used this 
way.

  Also, you should do the dictionary lookup first, in a try/except, 
and then execute it later, _outside_ the try/except, otherwise you 
risk masking KeyErrors from exec'd code.

  Jp



More information about the Python-list mailing list