Skip to content

Instantly share code, notes, and snippets.

@pydanny
Last active February 25, 2025 20:31
Show Gist options
  • Save pydanny/4735683 to your computer and use it in GitHub Desktop.
Save pydanny/4735683 to your computer and use it in GitHub Desktop.
PEP 8 vs Relative Imports

Hmmm...

PEP 8 says: "Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable."

Does this mean that by using relative imports we are in ignoring PEP 8? What's the justification?

@tartley
Copy link

tartley commented Feb 8, 2013

So just to spell it out in longhand for the hard of thinking (me),

Implicit (old style) relative imports have long been discouraged, because you can't be sure whether they have found an identically named module somewhere else on your PYTHONPATH.

But explicit (new style) relative imports don't allow for importing from elsewhere on the PYTHONPATH, so are fine.

So, in module foo.current, next to package baz, which contains dah.

from foo.baz import dah # absolute import, OK
from baz import dah # implicit relative, bad
from .baz import dah # explicit relative, OK

Is that it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment