Passing Global Variables between imported modules

Christopher Koppler klapotec at chello.at
Mon Aug 4 12:14:54 EDT 2003


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

>Is there any way to access global variables defined from within an
>imported module?  For example, lets say have a file called test2.py
>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()
>mc.printGlobal()
>
>
>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 test2.py 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 "globalTest.py", line 1, in ?
    from test2 import MyClass
  File "C:\Python23\test2.py", line 1, in ?
    from globalTest import globalVar
  File "C:\Python23\globalTest.py", 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
it.



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:

#test2.py
class MyClass:
    def __init__(self, val):
        self.value = val
    def printGlobal(self):
        print self.value

#globalTest.py
from test2 import MyClass

globalVar = "foo"

mc = MyClass(globalVar)
mc.printGlobal()



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...


--Christopher




More information about the Python-list mailing list