Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python packages - import by class, not file

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?

like image 472
Ellen Teapot Avatar asked Sep 05 '08 02:09

Ellen Teapot


People also ask

How can I import modules if file is not in same directory?

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.

What is __ init __ py for?

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.

How do I create an importable file in Python?

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.


1 Answers

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 
like image 194
dF. Avatar answered Sep 29 '22 07:09

dF.