[Python-Dev] Relative import

Devin devin at whitebread.org
Mon Dec 22 13:36:45 EST 2003

I've been monitoring all of this discussion about relative imports, and 
have my own humble idea about how to spell relative imports.

The first part stems from Guido's idea about using a '.' at the beginning 
of a relative import.  It seemed a bit weird at first, but I eventually 
became very comfortable with the idea after thinking about it in respect 
to absolute imports.  I'll explain what I mean.

If you currently want to import a module 'a.b.c.d', you write:

    import a.b.c.d

Now, if you're in the module 'a.b', you could still write:

    import a.b.c.d

... but the 'a.b' part is redundant because you're already in the module 
'a.b'.  If you take away 'a.b', then you end up with:

    import .c.d

This flowed well in my head, and looks natural.  However, the suggestion
about '.' or '..' referring to the parent looks _ugly and unnatural_.

Let's say '.' was used to spell "parent module", and let's assume that 
the module 'a.b.c.d' wants to import 'a.b.e'.  The absolute import would 
be spelled:

    import a.b.e

... and the relative import would be spelled:

    import .....e # .[parent].[parent].e

Yuck! (no offense :)

What's needed, I believe, is an identifier/keyword/symbol that spells
'parent' that isn't '.'.  Assuming that symbol is represented by
'[parent]', the above relative import would look like:

    import .[parent].[parent].e

... which is a hell lot more clear IMHO.

My initial idea is to spell parent '__parent__', and to have '__parent__'
be a module-level variable in each module that refers to the parent module
(where a top-level module might have '__parent__' refer to itself, or to
None).  Continuing with the above example, the relative import would be

    import .__parent__.__parent__.e

... but I'm not completely convinced that there's not a better 
identifier/keyword/symbol that could be substituted for '[parent]'.

If I'm completely off track, then tell me and I'll continue to lurk until
I get a better feel for the happenings of python-dev.

devin at whitebread.org

More information about the Python-Dev mailing list