Confused about closures and scoping rules

Rhamphoryncus rhamph at
Wed Nov 7 21:53:41 CET 2007

On Nov 6, 5:37 pm, "Chris Mellon" <arka... at> wrote:
> On Nov 6, 2007 6:23 PM, Jean-Paul Calderone <exar... at> wrote:
> > On Tue, 06 Nov 2007 17:07:47 -0700, Fernando Perez <fperez.... at> wrote:
> > > [snip]
> > >This struck me as counterintuitive, but I couldn't find anything in the
> > >official docs indicating what the expected behavior should be. Any
> > >feedback/enlightenment would be welcome.  This problem appeared deep inside a
> > >complicated code and it took me almost two days to track down what was going
> > >on...
> > Lots of people ask about this.  The behavior you observed is the expected
> > (by the implementors, anyway) behavior.
> Are there languages where closures *don't* behave like this? A closure
> that used a copy of the state rather than the actual state itself
> doesn't seem as useful. For references sake, JavaScript (the only
> language that a) has closures and b) I have a handy way to test with)
> does the same thing.

I've never needed to repeatedly modify closure variables.  However, I
may not set them until after the function is defined.  A simple
example is that of a recursive function:

def foo():
    def bar():
        bar()  # useful work omitted
    return bar

Obviously, bar can't be set until after the function object is

Showing changes also matches the behaviour of globals, which is a good
thing IMO.

Adam Olsen, aka Rhamphoryncus

More information about the Python-list mailing list