how to write function that returns function

Paul Graham spam at bugbear.com
Wed May 15 19:04:05 EDT 2002


> You can't directly translate that.  Access to variable of enclosing
> scopes is read only (except in the case of global statements, but that
> doesn't help here).

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

Although you can't modify variables from outer scopes, you can
modify *parts* of them (which to me seems like the same thing...)

The reason this problem seems kind of artificial is that I don't
need to solve this actual problem.  I heard that recent Python
versions had added more support for lexical closures, and was 
curious how well Python works for the type of programming in 
Structure and Interpretation of Computer Programs; this is kind 
of a hello_world of that genre.  (It's not a homework problem, 
I swear.)

Incidentally, here is Perl 5 code someone sent me for this case:

sub foo {
  my ($n) = @_;
  return sub {return $n += $_[0]}}

--pg



More information about the Python-list mailing list