why is this namespace weirdness happening?

Fredrik Lundh fredrik at effbot.org
Wed Jan 10 12:14:54 EST 2001


Preston Landers wrote:
> I noticed some namespace/import behavior that seems weird to me.  It
> happens in both Python 1.5.2 and 2.0 (though the error message is
> different.) Sorry if this is a FAQ; maybe someone could briefly explain
> why this happens.
>
> file1.py:---------------------
>
> import file2
>
> def foo():
>     import file2
>     # the line below fails if the line above is cmted out
>     # but works fine if present
>     print "file2 bar: ", file2.bar
>     import file2
>     print "file2 baz: ", file2.baz
>
> foo()
>
> file2.py:---------------------
>
> bar = 1
> baz = 2
>
> ------------------------------
>
> It seems that on the file1 "bar" line, if the 'import file2' above it is
> commented out, the file2.bar reference will fail (file2 being the
> unrecognized item.)  Despite the 'import file2' at the top of the file.

didn't I just reply to a very similar question?

oh, yes.  here it is:

:::

From: "Fredrik Lundh" <fredrik at effbot.org>
Subject: Re: Name Error
Date: Wed, 3 Jan 2001

/.../

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.

/.../

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

:::

hope this helps!

Cheers /F

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list