[Python-Dev] Why does PEP 8 advise against explicit relative imports? (original) (raw)
Thomas Wouters thomas at python.org
Tue Jul 16 14:02:28 CEST 2013
- Previous message: [Python-Dev] Why does PEP 8 advise against explicit relative imports?
- Next message: [Python-Dev] Why does PEP 8 advise against explicit relative imports?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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.
What's the concrete benefit of using absolute imports that overcomes these significant shortcomings in maintainability and composability?
In my experience changing the name of a package is problematic for more reasons than just 'import'. We used to do the put-in-a-package thing for third-party packages at Google, and we quit doing it because it was just too painful: it's hard to find all the places that reference the package by name (think of import, or mucking in sys.modules), and it's extra problematic with packages that contain extension modules. You can't rename a package, even for 'vendoring a package', without carefully checking whether it'll work -- unless you don't care if it'll work, of course :) The alternative is to include a package without changing its name (by adding the right directory, without init.py, to sys.path) and that has worked out a lot better for us.
Even so, there's no reason for the standard library to use explicit relative imports, and that's what PEP 8 is supposed to cover, right? :)
-- Thomas Wouters <thomas at python.org>
Hi! I'm an email virus! Think twice before sending your email to help me spread! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20130716/aaad9e4a/attachment.html>
- Previous message: [Python-Dev] Why does PEP 8 advise against explicit relative imports?
- Next message: [Python-Dev] Why does PEP 8 advise against explicit relative imports?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]