[Python-Dev] closure semantics

Guido van Rossum guido at python.org
Fri Oct 24 14:30:49 EDT 2003

> > > well, no, it's probably that I expect rebindable closed-over vars to
> > > be introduced but some kind of structured construct instead of the
> > > usual Python freeform.

> >Why does rebindability make a difference here?  Local vars are already
> >visible in inner scopes, and if they are mutable, they are already
> >being modified from inner scopes (just not rebound, but to most
> >programmers that's an annoying detail).

> most Python programmers or most Python programmers using closures?

I meant both categories.

> Well, it's a gut feeling, let's try to articulate it. Because
> a) parametrizing a closure with some read-only variable
> b) possibly shared mutable state with indefinite extent
> are very different things. I think that people should recur to b) instead 
> of using classes sparingly and make it clear when they do so.

Raymond's tree() example is an unfortunate one in this category.
(Unfortunately because it is obfuscated code for speed reasons and
because it appears in an examples section of official docs.)

> b) can feel like global variables with their problems, I think that's why I 
> would prefer a syntax that still point out: this is some state and this are 
> functions to manipulate it. Classes are fine for that, and knowing that it 
> is common style/idiom in Lisp variants this is also fine there:
>   (let ... introduces vars
>       ... function defs)
> I think it is also about expectations when reading some code. Right now, 
> reading Python code I expect at most to encounter a), although b) can be 
> obtained using mutable objects, but also in that case IMHO an explicit 
> uniform idiom would be preferable, like some Ref object inspired by ML 
> references.
> I can live with all solutions, although I'm still unconviced apart from the 
> Scheme textbook argument (which was serious) that this addition is really 
> necessary.

I don't think the Scheme textbook argument should weigh much, since
that's such a small audience.

My original approach has been to discourage (b) by not allowing
rebinding.  Maybe this should stay the way it is.  But the use of
'global x in f' might be enough to tip the reader off -- not quite at
the start of f, when x is defined, but at least at the start of the
inner function that declares x global in f.

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-Dev mailing list