Python Coding Style – What’s Wrong with Relative Imports?

coding-stylepython

I recently upgraded versions of pylint, a popular Python style-checker.

It has gone ballistic throughout my code, pointing out places where I import modules in the same package, without specifying the full package path.

The new error message is W0403.

W0403: Relative import %r, should be %r

Used when an import relative to the package directory is detected.


Example

For example, if my packages are structured like this:

/cake
  /__init__.py
  /icing.py
  /sponge.py
/drink

and in the sponge package I write:

import icing

instead of

import cake.icing

I will get this error.


While I understand that not all Pylint messages are of equal importance, and I am not afraid to dismiss them, I don't understand why such a practice is considered a poor idea.

I was hoping someone could explain the pitfalls, so I could improve my coding style rather than (as I currently plan to do) turning off this apparently spurious warning.

Best Answer

The problem of import icing is that you don't know whether it's an absolute import or a relative import. icing could be a module in python's path, or a package in the current module. This is quite annoying when a local package has the same name as a python standard library package.

You can do from __future__ import absolute_import which turns off implicit relative imports altogether. It is described, including with this justification about ambiguity, in PEP 328. I believe Python 3 has implicit relative imports turned off completely.

You still can do relative imports, but you have to do them explicitly, like this:

from . import icing
Related Topic