[Python-Dev] Why does PEP 8 advise against explicit relative imports?
Nick Coghlan
ncoghlan at gmail.com
Tue Jul 16 14:27:03 CEST 2013
On 16 July 2013 22: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.
>
>>
>> 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.
These are good reasons, but they're not the reasons the PEP currently
gives. "Better failure modes" is a good practical benefit :)
> 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? :)
I realised in re-reading the whole thing that we actually admitted
defeat on that front back during the last function annotations
discussion :)
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-Dev
mailing list