[Python-Dev] Relative import

Guido van Rossum guido at python.org
Tue Dec 16 13:26:59 EST 2003

A lot people have presented a good case for relative imports.  Nobody
has argued to keep the status quo (where imports are ambiguous about
whether they are meant to be absolute or relative).  So I suggest that
in 2.4, we introduce the leading dot notation for relative import,
while still allowing relative import without a leading dot.  In
2.5 we can start warning about relative import without a leading dot
(although that will undoubtedly get complaints from folks who have
code that needs to work with 2.3 still).  In 3.0 we can retire
ambiguous import.

The use case for multiple dots should be obvious: inside a highly
structured package, modules inside one subpackage must have a way to
do relative import from another subpackage of the same parent package.

There is the remaining issue of what exactly the syntax would be.  I
propose to extend the from clause to allow one or more dots before the
dotted name, and to make the dotted name optional if at least one
leading dot is found.  I propose not to change from-less import.

  from .foo import bar
  from .foo.bar import xxx
  from . import foobar as barfoo
  from ..foo.bar import *
  from ... import foobar, barfoo

Grammar change (see Grammar/Grammar):

dotted_name: NAME ('.' NAME)* | '.'+ [NAME ('.' NAME)*]

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-Dev mailing list