David G. Wonnacott wrote: > 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. >
Not using an anonymous function certainly sounds to me like the most "idiomatically appropriate Python way" to do this. def fourx(x): threex = 3 * x return x + threex map(fourx, [5, 17, 49.5]) The advantages over the lambda include the ability to use local variables and split the function naturally over multiple lines. Also you get to use a meaningful name to describe the function. -- http://mail.python.org/mailman/listinfo/python-list