Modifying func_closure

Terry Reedy tjreedy at
Sat Jul 10 02:00:15 CEST 2004

"Christopher T King" <squirrel at WPI.EDU> wrote in message
news:Pine.LNX.4.44.0407090956181.906-100000 at
> On 9 Jul 2004, Jacek Generowicz wrote:
> > I'm trying to do something like the following. (I'm no Schemer, so
> > there may well be a more concise way of putting it.)
> >
> >   (define closures
> >     (let ((enclosed 1))
> >       (define (report) enclosed)
> >       (define (modify new) (set! enclosed new))
> >       (list report modify)))
> >
> >   (define report (car closures))
> >   (define modify (cadr closures))
> >
> >   (report)    ; -> 1
> >   (modify 2)
> >   (report)    ; -> 2
> >
> > The mechanism isn't important, it's the effect: "enclosed" is rebound;
> > it's value changes in a way which all enclosing closures notice.

> Is there a reason you couldn't encapsule the functions and 'enclosed' in
> class (assuming you can move the function definitions into a class)?

This is the Python mechanism for getting the effect of multiple functions
accessing shared persistent but rebindable variables ('shared state' as
Guido puts it).  Guido added read-only closures primarily, I believe, as a
substitute for the default argument hack.  Notice that default args are
also read-only, and that the change required no syntax change, merely
either a legalization of previously illegal (NameError-raising) code or a
sematic change in having intermediate scope vars mask global or builtin
vars.  He had so far rejected sevaral proposals for adding syntax to make
closures mutable, noting that classes already do mutable shared state (and
perhaps also that one can instead use a mutable enclosed object).

Terry J. Reedy

More information about the Python-list mailing list