global name space and importing

David Goodger dgoodger at bigfoot.com
Sat May 27 23:02:33 EDT 2000


on 2000-05-27 20:47, Curtis Jensen (cjensen at bioeng.ucsd.edu) wrote:
> How come the global declaration works when I define it from withing the
> interpreter, but not from within a file that I import?

Because global means "global at the module level". There is no sharing of
globals between modules (if there were, what chaos that would create!). When
you're working in the interactive interpreter, you are actually in the
"__main__" module's namespace. When you import a module (regardless of
whether you use "import x" or "from x import *"; the latter just copies all
of x's names into the current namespace), you create a new namespace for
that module. Any global variables created by that module are global within
that module's namespace. For example, assume file mytest.py contains:

    def spam(i):
        global x
        x = i

So "x" will be global in mytest's namespace, rather than just local to the
spam() function.

Now let's test it:

    >>> from mytest import *
    >>> spam(5)
    >>> x
    Traceback (innermost last):
      File "<input>", line 1, in ?
    NameError: x

This is as you saw. Now, let's "import sys". "sys.modules" is a dictionary
contining all imported modules, indexed by name:

    >>> import sys
    >>> sys.modules["mytest"]
    <module 'mytest' ...>
    >>> sys.modules["mytest"].x
    5

So x *was* changed, in mytest's global namespace, but not __main__'s.

When you define a function in the interpreter:

    >>> def eggs(i):
    ...     global z
    ...     z = i
    >>> eggs(5)
    >>> z
    5

The function "eggs()" is defined in the "__main__" module, in __main__'s
namespace, therefore "global z" makes z a global variable in __main__'s
namespace.

Get it? :-)

-- 
David Goodger    dgoodger at bigfoot.com    Open-source projects:
 - The Go Tools Project: http://gotools.sourceforge.net
 (more to come!)




More information about the Python-list mailing list