I am currently working on a Python package. The package can be imported or it can also run from command line with -m
switch. Inside the package I am building a dependency injection container using - python-dependency-injector.
Now, here is my understanding of the __init__.py
and __main__.py
files -
- If package is imported - the content of
__init__.py
is executed. - If package is ran from command line with
-m
- the content of__main__.py
is executed.
For me weirdly, in either cases content of both files is being executed. Either I import the package or run it from command line the control flows through __init__.py
to __main__.py
and so on. All I am doing inside these files is building the dependency injection container -
from .containers import Container
container = Container()
container.init_resources()
container.wire(packages=[__name__])
When I run the package from command line I also get a RunTimeWarning as -
RunTimeWarning: 'package.__main__.py' found in sys_modules after import of package 'package', but prior to execution of 'package.__main__'; this may result in unpredictable behavior
And to fix this I added del sys.modules['package.__main__']
in __init__.py
.
Here is my folder structure -
src
\package
\__init__.py
\__main__.py
\readers
\__init__.py
\reader_module.py
\writers
\__init__.py
\writer_module.py
\utility
\__init__.py
\container_module.py
test.py <-- imports the package