[Python-ideas] Packages and Import

Josiah Carlson jcarlson at uci.edu
Sun Feb 11 11:22:04 CET 2007

Josiah Carlson <jcarlson at uci.edu> wrote:
> Anyways...I hear where you are coming from with your statements of 'if
> __name__ could be anything, and we could train people to use ismain(),
> then all of this relative import stuff could *just work*'.  It would
> require inserting a bunch of (fake?) packages in valid Python name
> parent paths (just in case people want to do cousin, etc., imports from
> __main__).
> You have convinced me.

And in that vein, I have implemented a bit of code that mangles the
__name__ of the __main__ module, sets up pseudo-packages for parent
paths with valid Python names, imports __init__.py modules in ancestor
packages, adds an ismain() function to builtins, etc.

It allows for crazy things like...

    from ..uncle import cousin
    from ..parent import sibling
    #the above equivalent to:
    from . import sibling
    from .sibling import nephew

...all executed within the __main__ module (which gets a new __name__). 
Even better, it works with vanilla Python 2.5, and doesn't even require
an import hook.

The only unfortunate thing is that because you cannot predict how far up
the tree relative imports go, you cannot know how far up the paths one
should go in creating the ancestral packages.  My current (simple)
implementation goes as far up as the root, or the parent of the deepest
path with an __init__.py[cw] .

If you are curious, I can send you a copy off-list.

 - Josiah

More information about the Python-ideas mailing list