Proposal for a modified import mechanism.
gmcm at hypernet.com
Sat Nov 10 23:52:38 CET 2001
Rainer Deyke wrote:
> Frederic Giacometti wrote:
>> I'd rather introduce a __parent__ module attribute (in addition to the
>> existing __name__) so that, for instance, the following would do your
>> from __parent__.__parent__.toto import something
> This wouldn't work without additional changes to the import mechanism,
> since the bindings of names are not used to resolve imports. Let's not
> add any more special cases.
I don't understand what you mean. The current import mechanism already
checks for a __parent__, and if there is one, tries a relative import.
This has been discussed before. IIRC, the main objections were that all the
ways of spelling it were considered too ugly.
Importing is a mapping between two hierarchical namespaces. The first of
these has some concept of "relative", but no way to spell it. Imagine trying
to work with a filesystem with those characteristics. Like Frederic, I'm
convinced that Python needs to learn to spell "relative" imports differently
from "absolute" imports. Personally, I favor doing it with the verb, not by
introducing path-like names.
>> I'm personnally against anything that enlarges the search path
>> uselessly; because the obvious reason of increased name space
>> collision, increased run-time overhead etc...
> The best way to avoid name collisions is to keep top-level names at an
> absolute minimum by placing modules in a deep hierarchy.
While I'd say the best way is to say what you mean. A deep hierarchy
introduces its own overhead.
> overhead may also be reduced this way, since many operating systems do
> a linear search over all files in a directory when opening a file.
Hmm. I experimented with an importer that cached os.listdir. There's some
kind of a threshold percentage-of-modules-hit over which the os.listdir
approach has an advantage, (my first-order guess is around 15%). It's
definitely a loss when only a few of the modules in that directory end up
As for os efficiency, I think that's pretty thoroughly stomped on by the
fact that Python will attempt to open 2, 3 or 4 files per entry on sys.path.
A successful relative import is minorly faster than the equivalent absolute
import, but obviously there's an net cost with a "try relative first, then
try absolute" strategy. The more "try relative to the one we just tried"
steps you stick in there, the costlier it becomes.
More information about the Python-list