2

Here is the code structure:

 my_project
├── __init__.py
├── main.py
└── util
    ├── __init__.py
    └── utility.py

When I run a program via python3 my_project/main.py.

I defined my_variable = 5 in my_project/__init__.py.

I want to access this my_variable at main.py and utility.py.

But have no idea how to do that....

I followed Can I use __init__.py to define global variables?, but it doesn't work for me (Cannot import project directory folder... it occurs an error : ImportError: No module named 'MY_PROJECT_DIR'..

Could you help this out?

Rob
  • 14,746
  • 28
  • 47
  • 65
user3595632
  • 5,380
  • 10
  • 55
  • 111

1 Answers1

2

For this you should be using relative import. Also python treats scripts and modules differently

content of my_project/__init__.py

my_variable = 5

content of my_project/util/utility.py

from .. import my_variable
print("my_variable", my_variable)

content of my_project/main.py

from . import my_variable
print("my_variable", my_variable )

running this as module

$ python3 -m my_project.util.utility
my_variable 5
$ 
$ python3 -m  my_project.main
my_variable 5
shanmuga
  • 4,329
  • 2
  • 21
  • 35