[Python-Dev] Relative import

Ken Manheimer klm at zope.com
Tue Dec 23 12:03:00 EST 2003

On Mon, 22 Dec 2003, Devin wrote:

> 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

I also look at it this way, and find it both intuitive and mnemonic.
My model is slighly different than yours, though, in a way that
simplifies the expression for going up the relative chain.  I'll

> 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 :)

Truly, yuck.  But in my model, the leading '.' dot, itself, stands for
the containing package, and '..' stands for the containing package's
package, and so forth:

  import ..e   #  [parent-of-parent].e

I don't think it's yucky at all, this way.  (I also don't think it's
un-pythonic - python uses punctuation all over to denote type literals
('{'/'}'), cues which delineate statement suites (':'), and so forth.)
In fact, i think it's a lot more mnemonic and encompassing than the
alternatives that use words (though i haven't looked at all the
alternatives very carefully yet).

Even using the leading '.' syntax, it would be good to have a specific
identifier for the containing package, realized in each module and
respected as a special identifier by the package machinery.  I like

  import __pkg__.sibling                # == 'import .sibling'


  import __pkg__.__pkg__.uncle          # == 'import ..uncle'
  import __pkg__.__pkg__.uncle.cousin   # == 'import ..uncle.cousin'

I think the leading '.' dot forms are a lot nicer, but the presence of
a module named '__pkg__' would be useful for programmatically mucking
navigating the package structure.

Ken Manheimer
klm at zope.com

More information about the Python-Dev mailing list