David Barishev David Barishev - 5 months ago 51
Python Question

Global Variable across modules

I faced this problem while i was expirementing with my project.My project is designed so it has multipule submoudles.

Now each submodule needs a position of an the same item on the screen,which is random each time the program ran.I thought it was a good idea to check once where is the position of the item (It does not change in runtime) , and let all modules access the position.(Since checking the position takes a long time)

This is what i did:

main.py



import Config
import sub_module

main()

def main():
position = get_pos()
Config.pos = position
sub_module.click_on_item()


Config.py



pos = None


I tried using this code , so when i ran the program , it sets the
config.py
module
pos
variable , to the position of the item on screen.

This code works fine but when i try to use it in the submodules like this:

sub_module.py



import Config

def click_on_item():
click(Config.pos)


It resets the value to None , since it reruns the
Config
module code.

Is there an elegant solution for this problem ? I can't let the position as an argument for the , since my case is much more complex.

One solution that i can think of is writing to the disk , and rereading but it's not fast.

Thanks for the help.

2 EDIT:



My project is multi-package , and there is the problem
this is the directory tree:

mainPackage:
__init__.py
Config.py
main.py
b.py
Packages:
Package_A:
__init__.py
a.py


main.py



import Config
from Packages.Package_A import a
import b

def main():
Config.Position = (124, 586)
a.print_val()
b.print_val()

if __name__ == '__main__':
main()


Config



Position = None


b.py



import Config

def print_val():
print Config.Position


a.py



from mainPackage import Config

def print_val():
print Config.Position


output



None -> from Package_A
(124, 586) -> from b.py


Sorry for the inconvenience since i didn't know what was causing the problem , my interest is in multi package global variable.

Answer

The problem is in a.py: from mainPackage import Config. You did an absolute import from a package and ended up importing Config twice. Python only imports a module once but in your case you used two different names (Config in some files, mainPackage.Config in others) which confused python and it imported the module twice - once by a package relative import and once by an absolute import. Add print "Importing Config" to Config.py and you will see it printed twice.

Just change a.py to import Config and all will be well.