Thursday, October 21, 2010

Python Import Search Order/Precedence

The Problem


I recently ran into an interesting (and very frustrating error). The error was:
ImportError: No module named apps.core.models
This error was happening to me in a django project. The package structure was as follows:

foo/
apps/
core/
models.py
auth/
foo/
models.py
views.py


In views.py I had the import statement:
from foo.apps.core.models import AModel

This was very confusing to me. Even worse was that the exact same statement worked just fine from the apps.auth.foo.models module.

The Explanation


The problem here has to do with how python handles searching for modules. You can read about it here.
To summarize python searches (in this order):
  1. The folder of the current module.
  2. Each folder listed in the PYTHONPATH.
  3. System specific folders ("set path", "export path", etc).

The Solution


The real problem I was running into was that the current folder had a foo module. So the full name that it was actually looking in was foo.apps.auth.foo.apps.core.models. To solve this I just needed to either change the package names (which really may be the best idea), or change the import statements to use a relative import path.

Something like this:
from ..core.models import AModel


Happy pythoning!