how to write function that returns function

Ian Bicking ianb at colorstudy.com
Tue May 14 19:10:26 EDT 2002


On Tue, 2002-05-14 at 18:03, Paul Graham wrote:
> 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.

This is the typical way of doing it, and yes, it is somewhat flawed.

In Python 2.1+ you can do:

from __future__ import nested_scopes

def addn(x):
    return lambda y: x+y

  Ian







More information about the Python-list mailing list