[Python-Dev] Why does PEP 8 advise against explicit relative imports?

Nick Coghlan ncoghlan at gmail.com
Wed Jul 17 04:38:54 CEST 2013


On 17 July 2013 11:55, Steven D'Aprano <steve at pearwood.info> wrote:
> On 16/07/13 22:02, Thomas Wouters wrote:
> As I see it, if relative imports are a bad idea for the std lib, they're a
> bad idea for everyone. (What am I missing?) So why do we have relative
> imports? Was it a mistake? I don't think so.
>
> It seems to me that you're giving some fairly obscure edge cases, if I've
> understood you correctly. If adding a package directory to sys.path breaks
> relative imports, isn't that an argument against adding the package
> directory to sys.path rather than relative imports?

What Thomas is saying is that, given the current state of the import
system, using absolute imports usually give you better behaviour (or
at least better error messages) than explicit relative imports do when
things go wrong. At present, there are still too many ways to get your
import configuration into a bad state (most notably running a module
inside a package by filepath rather than the -m switch), and if that
happens, using absolute imports is likely to make it a bit easier to
find your way out again.

I actually agree with that rationale - while I prefer explicit
relative imports myself, I'm also more experienced than most when it
comes to identifying and resolving import configuration problems (see
http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html)

So, for now, avoiding even explicit relative imports is still a good
default position. People who feel qualified to reject PEP 8's advice
on this topic should also know enough to deal with the potential
consequences. I'll be proposing a rewording of this admonition to give
a better rationale, but I won't be proposing that the recommendation
be changed :)

Once we get sys.path initialisation to a better place (amongst other
things), then it will be time to revisit the recommendation itself.

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list