I’m trying to access a module’s data from inside its __main__.py
.
The structure is as follows:
mymod/
__init__.py
__main__.py
Now, if I expose a variable in __init__.py
like this:
__all__ = ['foo']
foo = {'bar': 'baz'}
How can I access foo
from __main__.py
?
The
__init__
module of a package acts like members of the package itself, so the objects are imported directly frommymod
:Or
if you like to be terse, then read about relative imports. You need to make sure, as always, that you do not invoke the module as
mymod/__main__.py
, for example, as that will prevent Python from detectingmymod
as a package. You may wish to look intodistutils
.You need to either have the package already in
sys.path
, add the directory containingmymod
tosys.path
in__main__.py
, or use the-m
switch.To add
mymod
to the path would look something like this (in__main__.py
):Using the
-m
switch would like:See this answer for more discussion.
If you run the module with
python -m mymod
then code in__main__.py
will be able to import from the rest of the module without having to add the module tosys.path
.Module directory structure is as follows:
__init__.py
__main__.py
Execute the module as a script using the
-m
flag$ python -m py
The issue I run into the most with this type of thing is that I often want to run the
__init__.py
file as a script to test features, but these should not be run when loading the package. There is a useful workaround for the different execution paths betweenpython <package>/__init__.py
andpython -m <package>
.$ python -m <module>
executes<package>/__main__.py
.__init__.py
is not loaded.$ python <package>/__init__.py
simply executes the script__init__.py
like a normal script.The problem
When we want
__init__.py
to have anif __name__ == '__main__': ...
clause that uses stuff from__main__.py
. We can’t import__main__.py
because it will always import__main__.pyc
from the interpreter’s path. (Unless…we resort to absolute path import hacks, which can cause a lot of other mess).The solutionA solution :)Use two script files for the module’s
__main__
:The imports in
main.py
are probably not ideal in the case we are running from__init__.py
, as we are reloading them into the local scope of another module, despite having loading them in__init__.py
already, but the explicit loading should avoid circular loading. If you do load the entire__init__
module again in yourmain.py
, it will not be loaded as__main__
, so should be safe as far as circular loading is concerned.