Question about nested scopes

Michael Chermside mcherm at mcherm.com
Wed Oct 8 10:51:10 EDT 2003


Miki Tebeka:

The statement
    s += 4
rebinds s. Actually, sometimes, for certain mutable values,
it will rebind s to the same object that s used to be bound
to, but for some values (eg: immutables) it will bind s to
a new object. In all cases it counts as a binding statement.

On the other hand, the statement
    s[0] += 4
modifies the value in s[0]. It does NOT rebind s.

A function (whether nested or not, that's not the issue)
which accesses a global or outer-scope variable falls into
one of two categories: those that rebind the variable 
someplace, and those that don't. If it DOESN'T rebind the
variable anywhere, then the access to a global or outer-
scope variable is fine. If it DOES rebind the variable
someplace, though, then it's assumed to be a LOCAL
variable instead (which produces your error about accessing
the local variable before assigning it). If you really
want to rebind a global variable, then use the "global"
statement. If you really want to rebind an outer-scope
variable, then you're out of luck... there's no way to
acomplish that in Python (2.3 and under), so you'll
have to try returning the object from the function each
time, or enclosing it in a one-element list (like you
did), or using a simple class-with-one-attribute
wrapper, or one of the other tricks to get around this.

-- Michael Chermside







More information about the Python-list mailing list