how to write function that returns function
Kragen Sitaker
kragen at pobox.com
Wed May 15 17:34:39 EDT 2002
spam at bugbear.com (Paul Graham) writes:
> def addn(x):
> return lambda y,z=y: x+z
(assuming you mean lambda y,z=x: x+z)
>
> but I don't think this is exactly the same thing,
> because it returns a function that takes a second
> optional argument. That is a substantial difference.
This is embarrassing, which I guess is why we have nested scopes in
2.1+ so we don't have to do this any more; but here's a solution for
1.5.2:
class addn:
def __init__(self, x): self.x = x
def __call__(self, y): return self.x + y
This is a class instead of a function, but that is not a substantial
difference.
Unlike the nested-scopes case, this lets you modify the state of the
object in a straightforward way; a "counter" closure in Python is
ugly:
def counter(startvalue):
state = [startvalue]
def counter_internal():
state[0] += 1
return state[0]
return counter_internal
The class equivalent is a little better:
class counter:
def __init__(self, startvalue): self.state = startvalue
def __call__(self):
self.state = self.state + 1
return self.state
(I didn't use += because this class version will work in 1.5.2 and
earlier Pythons, which don't have +=. The nested-scopes version
doesn't.)
More information about the Python-list
mailing list