[Python-Dev] closure semantics

Guido van Rossum guido at python.org
Tue Oct 21 18:51:59 EDT 2003

[Changing the subject.]

> this is a bit OT and too late, but given that our closed over
> variables are read-only, I'm wondering whether, having a 2nd chance,
> using cells and following mutations in the enclosing scopes is
> really worth it, we kind of mimic Scheme and relatives but there
> outer scope variables are also rebindable. Maybe copying semantics
> not using cells for our closures would not be too insane, and people
> would not be burnt by trying things like this:
> for msg in msgs:
>    def onClick(e):
>      print msg
>    panel.append(Button(msg,onClick=onClick))
> which obviously doesn't do what one could expect today. OTOH as for
> general mutability, using a mutable object (list,...) would allow
> for mutability when one really need it (rarely).

It was done this way because not everybody agreed that closed-over
variables should be read-only, and the current semantics allow us to
make them writable (as in Scheme, I suppose?) if we can agree on a
syntax to declare an "intermediate scope" global.

Maybe "global x in f" would work?

def outer():
    x = 1
    def intermediate():
        x = 2
        def inner():
            global x in outer
            x = 42
        print x      # prints 2
    print x          # prints 42

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

More information about the Python-Dev mailing list