global vars across modules

Chris Angelico rosuav at gmail.com
Sun Apr 22 16:21:34 EDT 2012


On Mon, Apr 23, 2012 at 6:08 AM,  <mamboknave at gmail.com> wrote:
> Thanks! Here is what I need to do, perhaps you can give me some hints.
>
> A generic module, used across different independent programs, puts its computing results in a var fairly big, ~50KB.
>
> I need the functions in these programs to access that var. No assignment will be made to that var, it will just be accessed to parse its content.

Ah, then that's easy. There's two issues you have here:
1) When you "import * from some_module", you're taking every global
variable in that module and getting another reference to each of them.
Assigning to the global doesn't reassign to the imported variable.
2) You're working inside functions (funct_1 and main), and assigning
inside those functions, so the variables have function scope.

Problem 2 could be solved with the "global" keyword. Problem 1 is
solved by using a different data type for your global such as list or
dict, and then mutating it rather than reassigning it. Try this:

# file_1.py
a = []
def funct_1() :
   a.append(1)
   print("funct_1: %r"%a)

# file_2.py
from file_1 import *
def main():
	print("main: %r"%a)
	funct_1()
	print("main: %r"%a)
	a.append(2);
	print("main: %r"%a)
	funct_1()
	print("main: %r"%a)

main()
# end

file_1.py has a global called 'a', which is initially an empty list.
Nothing ever reassigns it, so file_1's a always points to that list.
Then file_2 imports that, which is equivalent to "a = file_1.a" (among
other things); this takes another reference to the same list. Then
everything appends to the list, or in whatever other way mutates it,
and both modules see the same changes.

Another way to solve this would be to use a non-from import:

# file_2.py
import file_1
print(file_1.a)

This is "reaching into" that module's globals, instead of taking a
copy. Untested but this should work.

Hope that helps!

ChrisA



More information about the Python-list mailing list