I’m writing a modular application that will dynamically import modules at runtime based upon launch parameters, etc. To keep things organised, I have the following directory structure:
myapp/
├── __init__.py
├── main.py
├── utils.py
├──modules/
├── __init__.py
├── iptables/
│ ├── __init__.py
│ ├── iptables.py
│ ├── [other files/directories/configuration...]
│ └── tests
│ ├── iptables_tests.py
├── layer4/
│ ├── __init__.py
│ ├── layer4.py
│ ├── [other files/directories/configuration...]
│ └── tests
│ ├── layer4_tests.py
I’m trying to accomplish the following:
-
main.pyshould be able to do something likefrom modules.layer4 import Layer4Manager, withLayer4Managerbeing a class insidemodules/layer4/layer4.py. I’d like to do this without including the actual code inside__init__.pyif possible, as there will be other scripts/files in the same directory, so it makes sense for them to be grouped together in directories (this is also why the scripts aren’t just in themodulesdirectory). -
iptables.pyandlayer4.pyshould be able to import functions fromutils.py. -
Tests using the Python unittest framework and Nose should run correctly by, for example,
iptables_tests.pyshould be able to runfrom myapp.modules.iptables import IPTablesControllerandfrom myapp.utils import UtilityFunction.
I’ve been battling with this for a few hours now and I’m unable to get all three of the above items working at the same time. Using from layer4 import * or the __all__ variable inside modules/layer4/__init__.py breaks the tests, as they are unable to from myapp.utils import UtilityFunction.
Blanking modules/*/__init__.py stops me from being able to from myapp.modules.layer4 import Layer4Manager.
I’ve tried several other combinations and I think I’m just making matters worse. I’m targeting Python 2.6. I’m guessing some kind of relative import will make things easier, but I’m not sure how they would work with the two-level directory structure I’m using here.
Thanks in advance!
You don’t need
main/__init__.pybecause you don’t want to makemyappa package and when you will execute main.py, myapp will be automatically added to python path.Other than that it looks fine, you should be able to directly import modules from subpackages if you put the correct paths e.g.
I created a similar structure and it works well e.g.
and all this works without error