Python packages - import by class, not file

PythonPackages

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEllen TeapotView Question on Stackoverflow
Solution 1 - PythondF.View Answer on Stackoverflow