I have a hello1 package that contains good.py module.
hello1
├── __init__.py
└── good.py
The init module has a variable A = 1
, and I need to access the variable hello1.A in good.py.
import hello1
class Good(object):
def __init__(self):
print hello1.A
if __name__ == "__main__":
g = Good()
The issue is that when I execute the python script I got ImportError: 'No module named hello1'
error. I could add import sys; sys.path.append("..")
at the first line of good.py
for a quick fix.
However, the good.py is in hello1 package where the __init__.py is also in, so I wonder if there is a way to access the variables in __init__.py from the modules in the same package.
From Python: import the containing package:
Importing
__init__
seems to work fine.If I'm not mistaken you want to do something like:
Since
good.py
is a submodule of a package you shouldn,'t run it directly; keep in mind that when directly executing it, then it isn't considered as part of thehello1
package, which prevents relative imports and the current directory is the one that contains the file, hencehello1
cannot be found if it isn't part of thePYTHONPATH
. Instead you can run it using the-m
switch of the python interpreter:I personally don't like using the interpreter options to execute a python file. I'd rather have an independent launcher file
good.py
that imports thehello1.good
module and uses it to do what it has to do.If you don't like sys.path.append(...) you could run your script as
in the directory containing the "hello1"-directory or use the PYTHONPATH environment variable instead of sys.path.
You have to explicit import the constants you want to use.
It's preferable to have all your constants in a "config" file (i.e. config.py) ) and then if you want them in the package namespace, import them.
init.py file:
it's more clear that way