how to write function that returns function

David Eppstein eppstein at ics.uci.edu
Fri May 17 23:05:47 EDT 2002


In article <ac4g68$qt5$0 at 216.39.172.122>, bokr at oz.net (Bengt Richter) 
wrote:

> Yes, it's much clearer. But I just thought of the following,
> which seems to work, and seems to me also pretty clear:
> 
>  >>> def foo(n):
>  ...     def bar(i):
>  ...         bar.s += i
>  ...         return bar.s
>  ...     bar.s = n
>  ...     return bar
>  ...
>  >>> f=foo(4)
>  >>> f(3)
>  7
>  >>> f(10)
>  17
> 
> The function bar is accessible via its own closure and thereby the 
> attribute s. So the attribute namespace seems to work like an 
> assignable-within closure ;-)

Neat, I like this a lot better than the s=[n] trick.

-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/



More information about the Python-list mailing list