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.
Keeping your code in the same file as it grows makes your code difficult to maintain. At this point, Python modules and packages help you to organize and group your content by using files and folders. Modules are files with “. py” extension containing Python code.
Organize your modules into packages. Each package must contain a special __init__.py file. Your project should generally consist of one top-level package, usually containing sub-packages. That top-level package usually shares the name of your project, and exists as a directory in the root of your project's repository.
Instead of converting some parts of the code to C, they hide the entire python code inside a protective C layer. Then, if they want a module importable by python, they write a thin python extension on top of the C. Open source is a much easier way of life.
In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With