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@python
components: Documentation, Library (Lib)
messages: 252078
nosy: Patrick Maupin, docs@python
priority: normal
severity: normal
status: open
title: Absolute imports fail in some cases where relative imports would work
type: behavior
versions: Python 2.7, Python 3.2, Python 3.3, Python 3.4, Python 3.5, Python 3.6

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue25294>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to