P.S. Re: Python newbie needs constructive suggestions

David G. Wonnacott davew at cs.haverford.edu
Mon Jul 24 11:04:08 EDT 2006


In response to my question, ``What is the idiomatically appropriate
Python way to pass, as a "function-type parameter", code that is most
clearly written with a local variable?'', a number of you made very
helpful suggestions, including the use of a default argument; if one
wanted to give a name to the constant one in my original example,

   map(lambda x: x+1, [5, 17, 49.5])

one would write

   map(lambda x, one=1: x+one, [5, 17, 49.5])

I've been using this happily in several cases, but just discovered
that (of course), the variable "x" is not in scope until the
expression in the lambda, so if one wanted to, say, have a variable
that was 3*x, one could NOT write

   map(lambda x, threex=3*x: x+threex, [5, 17, 49.5])

[obviously there are easier ways to find 4*x, but I'm trying to keep
close to my simplified example].

I'll need to show the code to beginners, so I don't want to get into
the complexity of using the more advanced solutions that were
suggested (closures or callable classes), so I'm going to bail out in
such cases and just not use an anonymous function here.

I'm not sure there's really a question here, other than the implicit
"please let me know if there's yet another cool thing I can do here",
but I thought I'd add this postscript to my earlier postings for the
benefit of anyone following this thread. [I often see interesting
threads in the archive but am left with an unresolved question "I
wonder how that worked out"].

Dave Wonnacott




More information about the Python-list mailing list