By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,903 Members | 2,097 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,903 IT Pros & Developers. It's quick & easy.

How to share variables between modules?

P: 1
How do I share a module variable with another class module?
Ideally I want file2.py to inherit the variables+value from file1.py.

When I import a module, I want access to the variables (by reference), not a copy.

Expand|Select|Wrap|Line Numbers
  1. # file1.py
  2. import file2
  3.  
  4. var1 = None
  5.  
  6. def func1():
  7.     global var1
  8.     var1 = 'test'
  9.  
  10. if __name__ == "__main__":
  11.     func1()
  12.     print var1  # prove variable was modified.
  13.     f2 = file2.ClassA()
  14.     f2.func3()
  15.  
Expand|Select|Wrap|Line Numbers
  1. # file2.py
  2. import file1
  3.  
  4. class ClassA:
  5.     def func3(self):
  6.         print file1.var1
  7.  
Expand|Select|Wrap|Line Numbers
  1. Results:
  2. Test
  3. None
  4.  
Jun 22 '16 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.