How to organize Python source code files? [closed]
Question
I am developing a Python App Engine app, where I want to split the content of a source code file Models.py
into separate files for each model, but I want to put it all in a folder called Models. The problem is that when I do that, my app can't find the classes anymore. What should I do?
This question is not about MVC but another question with the same title is.
Solution
Put an empty __init__.py
file in the Models directory.
Then, in your app; presumably one level up, you reference modules in the Models directory like this:
import Models
and do something with it like this:
Models.my_model.MyClassName
You can also use the from
keyword like this:
from Models import my_model
and reference like this:
my_model.MyClassName
If you only need one method from a module, you could also do this:
from Models.my_model import my_method_name
my_method_name()
Obligatory link to the documentation.
OTHER TIPS
In response to your comment to Adam's answer, regarding having 10 imports for 10 classes, firstly don't forget that there's no need to have one class per module in Python. Modules should be organised by functionality, so you can group related classes in a single file if that makes sense.
If you still wanted to make all the classes importable in one go, you could import them all in the __init__.py
file itself using the from submodule import Class
syntax, then just import the containing module - import mainmodule
and refer to mainmodule.Class1
etc, or even use from mainmodule import Class1, Class2, Class3
to import the classes directly into your namespace and refer to them directly.
Adam Bernier provides a good technical description of how packages work. A great description of how to arrange and ship a project is described in http://jcalderone.livejournal.com/39794.html