[Python-Dev] Relative import
Guido van Rossum
guido at python.org
Wed Dec 17 12:21:57 EST 2003
It's interesting that the "scan upwards on the package name" gets so
much support. Back when packages were first introduced, there was a
period of time when they were a user-level construct, implemented by a
module named "ni" (after the Knights who say "Ni!"). This implemented
a full scan upward as the only way. When I reimplemented packages in
C, I decided that the scan wasn't used much, and could actually be
detrimental (I feared that too many global modules would be
accidentally hidden), so I changed it to only looking in only two
places: the current package and the toplevel (sys.path).
But at the time it was a given that the import syntax would not be
changed. Now that we're entertaining new import syntax, we can do
better. How about this for Python 3.0:
import P.Q (1)
from P.Q import X (2)
would only look for P in sys.path (I'll call this "absolute import");
and
from ...P.Q import X (3)
would scan for P upwards from the current package. It would require
exactly three dots. P.Q of course stands for any dotted name.
Python 2.x would continue to use the current ("ambiguous import")
semantics for (1) and (2), but would also support (3) with the Python
3.0 semantics.
It might also be possible to set a "no ambiguous imports" flag to
switch to 3.0 semantics for (1) and (2). This might be a __future__
statement in the package's __init__.py, e.g.
from __future__ import absolute_import
I think this addresses all the concerns I've seen brought up in this
thread so far against my original proposal and the variations that
were subsequently suggested.
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev
mailing list