0

I have a project with folder structure like this:

MainFolder/
    __init__.py
    Global.py
    main.py
Drivers/
    __init__.py
    a.py
    b.py

In Global.py I have declared like this:

#in Global.py file
global_value=''

Now when I tried the below script:

#in main.py
import Global
from Drivers import a
Global.global_value=5
a.print_value()

In a.py file

from MainFolder import Global
def print_value():
    print Global.global_value

The output supposed to be like this:

5

But all I am getting is :

''

Anyone with this solution what happens when context changes??

3
  • what version of python? Commented Feb 15, 2015 at 9:30
  • In my example I just had the two files in the same directory. I don't see the solution immediately and I don't have time to work on it. I've deleted my answer to increase the chances someone else finds this. But for me having Global.py and a.py in the same directory (and then running the commands in ipython) it did what you seemed to want. Commented Feb 15, 2015 at 10:55
  • Yeah. In same directory it got no problem.. but my file directory is like this.. so we needed it like that. Commented Feb 15, 2015 at 14:24

1 Answer 1

1

In my opinion you should not do that. To have some form of common value, write the value to a file/db and then fetch the value from that file.

If that doesn't suite the needs, here's some resources I found, might help you out:

I've not tested this, but this one should work (fetched from Import a module from a relative path)

 import os, sys, inspect
 # realpath() will make your script run, even if you symlink it :)
 cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
 if cmd_folder not in sys.path:
     sys.path.insert(0, cmd_folder)

 # use this if you want to include modules from a subfolder
 cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
 if cmd_subfolder not in sys.path:
     sys.path.insert(0, cmd_subfolder)

 # Info:
 # cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
 # __file__ fails if script is called in different ways on Windows
 # __file__ fails if someone does os.chdir() before
 # sys.argv[0] also fails because it doesn't not always contains the path

More:

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.