Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute Import Not Working, But Relative Import Does

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?

like image 573
LaSmell Avatar asked Aug 21 '16 20:08

LaSmell


People also ask

Should I use absolute or relative imports?

Remember that you should generally opt for absolute imports over relative ones, unless the path is complex and would make the statement too long.

How do I import absolute value in Python?

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.

What are the 3 types of import statements in Python?

Good practice is to sort import modules in three groups - standard library imports, related third-party imports, and local imports.


Video Answer


1 Answers

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.

like image 196
Martijn Pieters Avatar answered Sep 27 '22 17:09

Martijn Pieters