Name Error

Fredrik Lundh fredrik at effbot.org
Wed Jan 3 17:26:41 EST 2001


Curtis Jensen wrote:
> Oh, I see the problem.  I do assign to stored_data.  It works if I
> comment out the last line.  I didn't think that would cause
> "stored_data" to change scopes.

Inside a function or method, a name can be either local (in
the function's namespace) or global (in the module's name-
space).

To figure out what's what, Python's compiler looks for assign-
ments inside the function body.   Any name you assign to [1]
is considered to be local, any other name is global.

Note that affects all uses of a name inside a function body.
if you try to access a local variable before you've assigned
any value to it, Python will raise an exception, rather than
look in the module namespace.

To override this, you can use the "global" statement to mark
a name as belonging to the module namespace, even if you
assign to it:

    def send_data():
        global stored_data
        ...
        # clear stored_data
        stored_data = []

Note that modifying an object in place doesn't count as assign-
ment.  Here's an alternative (probably less efficient) solution:

    def send_data():
        ...
        # clear stored_data
        del stored_data[:]

> Would Python 2.0 not have this problem?

Not really -- but 2.0 says "UnboundLocalError" instead ;-)

Hope this helps!

Cheers /F

1) Assignments also include arguments (assigned during the call),
def/class statements, and imports.





More information about the Python-list mailing list