问题
Here is my app structure:
foodo/
setup.py
foodo/
__init__.py
foodo.py
models.py
foodo/foodo/foodo.py
imports classes from the models.py
module:
from foodo.models import User
which throws an ImportError
:
ImportError: No module named models
However, it does work if I use a relative import:
from models import User
And it also works if I put in an pdb breakpoint before the import and continue.
I should be able to use both absolute and relative imports right?
回答1:
You have a local module foodoo
inside the foodoo
package. Imports in Python 2 always first look for names in the current package before looking for a top-level name.
Either rename the foodoo
module inside the foodoo
package (eliminating the possibility that a local foodoo
is found first) or use:
from __future__ import absolute_import
at the top of your modules in your package to enable Python-3 style imports where the top-level modules are the only modules searched unless you prefix the name with .
to make a name relative. See PEP 328 -- Imports: Multi-Line and Absolute/Relative for more details.
来源:https://stackoverflow.com/questions/39068391/absolute-import-not-working-but-relative-import-does