2

I want to make a variable global to more than 2 files so that operating in any file reflects in the file containing the variable.

what I am doing is:

b.py

import a

x = 0
def func1():
    global x
    x = 1   
if __name__ == "__main__":
    print x
    func1()
    print x
    a.func2()
    print x

a.py

import b

def func2():
    print b.x
    b.x = 2

I have searched for threads here and find from a import * is making copies and import a is otherwise. I expect the code above to print 0 1 1 2(sure it should be in new lines) when execute python b.py but it's showing 0 1 0 1

How does one implement that?

onemach
  • 4,265
  • 6
  • 34
  • 52
  • You are making a cyclic import here.. importing b in a.py and a in b.py, instead you can only import the required x from a in b.py – avasal Jan 11 '12 at 04:59

1 Answers1

7

Let me start by saying that I think globals like this (using the global keyword) are evil. But one way to restructure it is to put your globals into a class in a SEPARATE module to avoid circular imports.

a.py

from c import MyGlobals

def func2():
    print MyGlobals.x
    MyGlobals.x = 2

b.py

import a
from c import MyGlobals

def func1():
    MyGlobals.x = 1   


if __name__ == "__main__":
    print MyGlobals.x
    func1()
    print MyGlobals.x
    a.func2()
    print MyGlobals.x

c.py

class MyGlobals(object):
    x = 0

OUTPUT

$ python b.py 
0
1
1
2
jdi
  • 90,542
  • 19
  • 167
  • 203
  • 1
    The module `c` itself could provide the globals, rather than wrapping them in a class. – chepner Jan 11 '12 at 05:15
  • why wrap with a class? without the class the problem is still there. – onemach Jan 11 '12 at 05:15
  • I only wrap it in a class because I feel its more appropriate in case you did want to pass it around or store it on another class as a configuration object, and not actually store a module object. – jdi Jan 11 '12 at 06:00