Say I have the following file structure:
app/ app.py controllers/ __init__.py project.py plugin.py
If app/controllers/project.py defines a class Project, app.py would import it like this:
from app.controllers.project import Project
I'd like to just be able to do:
from app.controllers import Project
How would this be done?
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.
You need to tell python to first import that module in your code so that you can use it. If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory.
You need to put
from project import Project
in controllers/__init__.py
.
Note that when Absolute imports become the default (Python 2.7?), you will want to add a dot before the module name (to avoid collisions with a top-level model named project
), i.e.,
from .project import Project
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