36

Are there any rules or guidelines concerning when to use relative imports in Python? I see them in use all the time, such as in the Flask web framework. When searching for this topic, I only see articles on how to use relative imports, but not why.

So is there some special benefit to using:

from . import x

rather than:

from package import x

Moreover, I noticed that a related SO post mentions that relative imports are discouraged. Yet people still continue to use them.

KJH
  • 2,382
  • 16
  • 26
trinth
  • 5,919
  • 9
  • 40
  • 45
  • Regarding the [referenced SO answer discouraging relative imports](https://stackoverflow.com/a/5811548/1918127), there's also a highly upvoted counterargument, "As of September 213 [sic], this answer is wrong because PEP8 has changed...". – mathandy Sep 21 '21 at 01:54

1 Answers1

32

Check out PEP 328's section on relative imports

The rationale seems to be as written:

Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-packages. In addition, a module inside a package can't easily import itself without relative imports.

Bartek
  • 15,269
  • 2
  • 58
  • 65
  • 13
    "a module inside a package can't easily import itself" What even does that mean? – endolith May 29 '22 at 17:59
  • 1
    @endolith Imagine having a package `a`, with a subpackage `b`. Without relative imports, module `a.b.m` can't import itself without knowing not only that it's part of package `b`, but also of package `a`. – rrrrrrrrrrrrrrrr Aug 23 '22 at 18:10