[docs] [issue25294] Absolute imports fail in some cases where relative imports would work
report at bugs.python.org
Sat Oct 3 21:21:22 CEST 2015
Patrick Maupin added the comment:
The PEP 8 recommendation to "use absolute imports" is completely, totally, unambiguously meaningless absent the expectation that packages refer to parts of themselves. And it works, too! (For a single level of package.)
As soon as packages are nested, this recommendation falls over, with the most innocuous code:
x/__init__.py: import x.y
x/y/__init__.py: import x.y.z; x.y.z
The ability to nest packages is an attractive nuisance from a programmer's perspective. He's neatly organized his code, and now he finds that there are two ways to make it work: (1) Use the disparaged relative imports; or (2) flatten his package to a single level, because importing X.Z from within X.Y will work fine.
IMO, the language that Nick proposes for PEP 8 will either (a) not be understood at all by the frustrated junior programmer -- sure, the import system views it as a circular import, but he's not seeing it that way; or (b) be understood to expose a huge wart on the side of Python: Even though Z is only used by Y/__init__, and doesn't itself use anything else in Y, it cannot live alongside Y/__init__. Instead, unless Y is a top level module or the programmer uses denigrated relative imports, he will now have to move it to a different place, so that from Y he can then "import X.Y_HELPER.Z".
Another PEP 8 prescription is that "Standard library code should avoid complex package layouts and always use absolute imports." Here's a serious offer -- I'll give $200 to whoever gets the patch accepted that makes lib2to3 conformant without breaking it.
Python tracker <report at bugs.python.org>
More information about the docs