[docs] [issue25294] Absolute imports fail in some cases where relative imports would work
report at bugs.python.org
Fri Oct 2 04:23:44 CEST 2015
New submission from Patrick Maupin:
PEP 8 recommends absolute imports over relative imports, and section 5.4.2 of the import documentation says that an import will cause a binding to be placed in the imported module's parent's namespace.
However, since (with all current Python versions) this binding is not made until _after_ the module body has been executed, there are cases where relative imports will work fine but absolute imports will fail. Consider the simple case of these five files:
xyz.py: import x
x/__init__.py: import x.y
x/y/__init__.py: import x.y.a
x/y/a/__init__.py: import x.y.b; foo = x.y.b.foo
x/y/b/__init__.py: foo = 1
This will fail in a fashion that may be very surprising to the uninitiated. It will not fail on any of the import statements; rather it will fail with an AttributeError on the assignment statement in x.y.a, because the import of y has not yet finished, so y has not yet been bound into x.
This could conceivably be fixed in the import machinery by performing the binding before performing the exec. Whether it can be done cleanly, so as not to cause compatibility issues with existing loaders, is a question for core maintainers.
But if it is decided that the current behavior is acceptable, then at a minimum both the PEP 8 and the import documentation should have an explanation of this corner case and how it can be solved with relative imports.
assignee: docs at python
components: Documentation, Library (Lib)
nosy: Patrick Maupin, docs at python
title: Absolute imports fail in some cases where relative imports would work
versions: Python 2.7, Python 3.2, Python 3.3, Python 3.4, Python 3.5, Python 3.6
Python tracker <report at bugs.python.org>
More information about the docs