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?
Remember that you should generally opt for absolute imports over relative ones, unless the path is complex and would make the statement too long.
Absolute imports in PythonAbsolute import involves a full path i.e., from the project's root folder to the desired module. An absolute import state that the resource is to be imported using its full path from the project's root folder.
Good practice is to sort import modules in three groups - standard library imports, related third-party imports, and local imports.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With