how to write function that returns function

George Demmy gdemmy at layton-graphics.com
Wed May 15 13:38:26 EDT 2002


spam at bugbear.com (Paul Graham) writes:

> Thanks to everyone who replied to my earlier question.  It seems
> Python scope rules have changed recently, and my info was out of 
> date.  I am still uncertain about a couple things though: there
> seem to be some restrictions on what you can do with lexical
> variables and also what you can put in a lambda.  Can some Python
> expert tell me how you would express the Common Lisp
> 
> (defun foo (n) #'(lambda () (incf n)))
> 
> in Python?
> 
> Many thanks,  --pg

Here's one way:

class foo:
  def __init__(self, n):
    self.n = n

  def next(self):
    self.n += 1
    return self.n

def mkfoo(n):
  f = foo(n)
  return f.next

bar = foo(1)

print bar(), bar(), bar()
-> 2 3 4

I don't think that the "Guido implementation" of Python allows the
capture of state in closures the same way that you can in Scheme and
CL, though you can fake it very easily, as above. 

G




More information about the Python-list mailing list