Python newbie needs constructive suggestions

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sat Jul 22 14:49:37 EDT 2006


davew-python at cs.haverford.edu a écrit :
> What is the idiomatically appropriate Python way to pass, as a
> "function-type parameter", code that is most clearly written with a
> local variable?

def functionWithLocal(andArg):
   localVar = 42
   return andArg+localVar

map(functionWithLocal, range(42))


> For example, map takes a function-type parameter:
> 
> map(lambda x: x+1, [5, 17, 49.5])
> 
> What if, instead of just having x+1, I want an expression that is
> most clearly coded with a variable that is needed _only_ inside the
> lambda, e.g. if I wanted to use the name "one" instead of 1:
> 
> map(lambda x: (one = 1  x+one), [5, 17, 49.5])

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

> This sort of thing is of course straightforward in many other
> languages with anonymous functions (Scheme, Haskell, Smalltalk, etc),
> and I saw in the archives the discussion from 2003 about "How do I
> get Scheme-like let bindings in Python". Many of the answers seem to
> boil down to "You should not write Scheme programs in Python, you
> should write Python programs in Python".

A very sensible advice IMHO. Python - while having some support for FP - 
is still statement-based and mostly on the OO/procedural side.

(snip)



More information about the Python-list mailing list