[Python-Dev] Why does PEP 8 advise against explicit relative imports? (original) (raw)

Ronald Oussoren ronaldoussoren at mac.com
Wed Jul 17 07:58:03 CEST 2013


On 16 Jul, 2013, at 14:02, Thomas Wouters <thomas at python.org> wrote:

On Tue, Jul 16, 2013 at 1:40 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:

PEP 8 advises developers to use absolute imports rather than explicit relative imports.

Why? Using absolute imports couple the internal implementation of a package to its public name - you can't just change the top level directory name any more, you have to go through and change all the absolute imports as well. You also can't easily vendor a package that uses absolute imports inside another project either, since all the absolute imports will break. The problem with relative imports (both explicit and implicit) is that it makes it less obvious when you are importing a module under the wrong name. If a package ends up in sys.path directly (for example, by executing something that lives inside it directly) then an explicit relative import directly in the package will fail, but an explicit relative import in a sub-package won't, and you can end up with the subtly confusing mess of multiple imports of the same .py file under different names.

That's only a problem for subpackages (that is, for example when distutils.commands ends up being importable as commands), because explicit relative imports (from .other import attr) don't work in toplevel modules or scripts because the leading dot means "the current package".

I tend to use explicit relative imports in my code when that increases readability by reducing unnecessary duplication. That is, readability tends to suffer when you have a number of lines like with "from package.module1 import name".

Ronald



More information about the Python-Dev mailing list