Python newbie needs constructive suggestions

Peter Otten __peter__ at web.de
Sat Jul 22 02:25:51 EDT 2006


davew-python at cs.haverford.edu wrote:

> What is the idiomatically appropriate Python way to pass, as a
> "function-type parameter", code that is most clearly written with a local
> variable?
> 
> 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])
 
For a simple constant expression, your example is how it's done most
frequently. When it gets more complicated the classic trick is to use a
default argument:

>>> map(lambda x, delta=2**10: x+delta, [5, 17, 49.5])
[1029, 1041, 1073.5]

A closure works equally well:

>>> def make_adder(delta):
...     def add(x):
...             return x + delta
...     return add
...
>>> map(make_adder(42), [5, 17, 49.5])
[47, 59, 91.5]

So does a callable class...

>>> class Adder(object):
...     def __init__(self, delta):
...             self.delta = delta
...     def __call__(self, x):
...             return x + self.delta
...
>>> map(Adder(321), [5, 17, 49.5])
[326, 338, 370.5]

which has the advantage that it can maintain state between calls (e. g. if
you were to build an accumulator it would be your only clean option).

In the real world the first two are most common, but they are only used when
the variable is not for immediate consumption:

# wrong
>>> adders = [lambda x: x + delta for delta in range(3)]
>>> [a(0) for a in adders]
[2, 2, 2]

# fixed
>>> adders = [lambda x, delta=delta: x + delta for delta in range(3)]
>>> [a(0) for a in adders]
[0, 1, 2]

> Do I
> 
>   d) give up on using Python and go back to Scheme, or

If you stick with Python your students can soon start to experiment with
concepts and algorithms, and at the same time you provide them with a tool
that may be useful in their daily work (think scipy).

Peter




More information about the Python-list mailing list