how to write function that returns function

Michael Hudson mwh at python.net
Wed May 15 12:34:08 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?

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).

The usual response to questions like this is "what is it you're
actually trying to *do*?"; there may well be a natural way of
acheiving *that* despite the fact that there are no non-horrible
direct translations of the above code (usually involving defining a
class or two...).

Cheers,
M.

-- 
  It's a measure of how much I love Python that I moved to VA, where
  if things don't work out Guido will buy a plantation and put us to
  work harvesting peanuts instead.     -- Tim Peters, comp.lang.python



More information about the Python-list mailing list