how to write function that returns function

Kragen Sitaker kragen at pobox.com
Thu May 16 03:25:44 EDT 2002


spam at bugbear.com (Paul Graham) writes:
> It looks as if the closest thing would be something like this,
> which a Python expert sent me:
> 
> def foo(n):
>   s = [n]
>   def bar(i):
>     s[0] += i
>     return s[0]
>   return bar

I don't think it's accurate to refer to me as a "Python expert".
Maybe someone else sent you essentially the same thing?

> Incidentally, here is Perl 5 code someone sent me for this case:
> 
> sub foo {
>   my ($n) = @_;
>   return sub {return $n += $_[0]}}

The final } should be on the next line for normal Perl style, and the
second 'return' is gratuitous.  (Neither 'return' is necessary, but
only the second one is bad style.)




More information about the Python-list mailing list