[Python-Dev] New relative import issue

Josiah Carlson jcarlson at uci.edu
Tue Sep 19 06:18:24 CEST 2006

Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Armin Rigo wrote:
> > there
> > is no clean way from a test module 'foo.bar.test.test_hello' to import
> > 'foo.bar.hello': the top-level directory must first be inserted into
> > sys.path magically.
> I've felt for a long time that problems like this
> wouldn't arise so much if there were a closer
> connection between the package hierarchy and the
> file system structure. There really shouldn't be
> any such thing as sys.path -- the view that any
> given module has of the package namespace should
> depend only on where it is, not on the history of
> how it came to be invoked.

Wait, wait, wait.  If I remember correctly, one of the use-cases cited
was for sub-packages of a single larger package to be able to import
other sub-packages, via 'from ..subpackage2 import module2'.  That is to
say, given a package structure like...


Running module1.py, with an import line that read:
    from ..subpackage2 import module2

... would import module2 from subpackage2

Testing this in the beta I have installed tells me:

Traceback (most recent call last):
  File "module1.py", line 1, in <module>
    from ..subpackage2 import module2
ValueError: Relative importpath too deep

While I can understand why this is the case (if one is going to be
naming modules relative to __main__ or otherwise, unless one preserves
the number of leading '.', giving module2 a __name__ of
__main__..subpackage2.module2 or ..subpackage2.module2, naming can be
confusing), it does remove a very important feature.

Guido suggested I make up a PEP way back in March or so, but I was
slowed by actually implementing __main__-relative naming (which is
currently incomplete).

As it stands, in order to "work around" this particular feature, one
would need to write a 'loader' to handle importing and/or main() calling
in subpackage1/module1.py .

 - Josiah

More information about the Python-Dev mailing list