Passing Global Variables between imported modules

Christopher Koppler klapotec at
Mon Aug 4 18:14:54 CEST 2003

On 4 Aug 2003 07:27:41 -0700, sean at (Sean) wrote:

>Is there any way to access global variables defined from within an
>imported module?  For example, lets say have a file called
>that defines a simple class:
>class MyClass:
>  def __init__(self):
>    pass
>  def printGlobal(self):
>    print globalVar
>Now I have another file that imports test2, sets a global variable
>called globalVar, and calles printGlobal() like so:
>from test2 import MyClass
>globalVar = "foo"
>mc = MyClass()
>When I run it, I get a NameError that "global name 'globalVar' is not
>defined".  I've tried explicitly calling 'global globalVar' and even
>stepping through the __builtins__ but to no avail.  Is accessing
>globalVar from within possible?

Global variables are global at *module* level, which means that every
class and function defined in that module can access that variable.
Variables (and all other names) from *other* modules need to be
imported in order to be used, thus the 'not defined'.

In your case, however, you'd need to import the 'another file that
imports test2' (I'll call it globalTest from here on) into test2, so
you could access globalVar inside of test2; that would lead to a nasty
case of circular import, and an ImportError exception will be thrown:

Traceback (most recent call last):
  File "", line 1, in ?
    from test2 import MyClass
  File "C:\Python23\", line 1, in ?
    from globalTest import globalVar
  File "C:\Python23\", line 1, in ?
    from test2 import MyClass
ImportError: cannot import name MyClass

There might be a hack around that, but if there was, I wouldn't use

To pass any value from globalTest to test2.MyClass, pass it at class
instantiation - it becomes a variable local to the class instance.
Directly adapting your example:
class MyClass:
    def __init__(self, val):
        self.value = val
    def printGlobal(self):
        print self.value
from test2 import MyClass

globalVar = "foo"

mc = MyClass(globalVar)

So far so good, this runs as it should.

Now if you tell us what you really wanted to do, maybe we could give
you a more helpful answer...


More information about the Python-list mailing list