61

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?

Adam Bellaire
  • 108,003
  • 19
  • 148
  • 163
Ellen Teapot
  • 1,580
  • 1
  • 14
  • 22

1 Answers1

104

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
dF.
  • 74,139
  • 30
  • 130
  • 136
  • 3
    I wonder if it is possible to exclude at all the ability to call `app.controllers.project.Project`, in order to avoid having redundant paths to the same object (having both `app.controllers.project.Project` and `app.controllers.Project` at this point) – Andrea Oct 27 '18 at 09:15