how to write function that returns function

Steve Holden sholden at holdenweb.com
Tue May 14 22:28:43 EDT 2002


"Paul Graham" <spam at bugbear.com> wrote in message
news:4f52f844.0205141503.40000c50 at posting.google.com...
> I am not a Python expert, and I'm hoping someone
> can tell me how in Python to write a function
> of one argument x that returns a function of one
> argument y that returns x+y.
>
> Here, in Scheme, is what I want to write:
>
> (define foo (x) (lambda (y) (+ x y)))
>
> I found on the web a page that says I could define
> this as follows:
>
> def addn(x):
>   return lambda y,z=y: 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.
> If the Scheme function is inadvertently called
> (e.g. in someone else's code) with two arguments, it
> would signal an error, whereas the code above would
> quietly give the wrong answer.
>
> I would appreciate it if someone could tell me the
> standard way to write this so that it returns a
> function of exactly one argument.
>
There's no need to use lambda, and indeed I eschew it whenever it make sense
to do so. From 2.2 on you don't need top import nested_scopes from
__future__, by the way. Since functions are fisrt-class objects, it doesn't
matter what name is associated with the declarations - they can be bound to
any variable once they are returned.

Python 2.2 (#1, Dec 31 2001, 15:21:18)
[GCC 2.95.3-5 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def adder(x):
...     def anyoldname(y):
...         return x+y
...     return anyoldname
...
>>> add3 = adder(3)
>>> add100 = adder(100)
>>> add3(12)
15
>>> add100(12)
112
>>>

Note, however, that the function name (the name bound to it in the def
statement) does get built in to its repr():

>>> add3
<function anyoldname at 0x100fffe8>
>>> add100
<function anyoldname at 0x10100278>
>>>

Hope this helps.

regards
 Steve
--
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------








More information about the Python-list mailing list