469,909 Members | 1,786 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,909 developers. It's quick & easy.

Relative import first impressions

Now 2.5 is out, and we have a syntax for explicit relative imports
(PEP 328, http://www.python.org/dev/peps/pep-0328/, in case anyone
wasn't paying attention). The long-term plan is that the classical
import syntax becomes absolute import only, so that all imports are
explicitly one or the other.

You can only use relative import from within packages. Trying to
import a top-level module relatively from within same directory,
produces the exception "ValueError: Relative importpath too deep".

There's a certain logic to that: You can just omit "from ." and do a
regular absolute import. However, that spells bad news for modules
that are both contained within packages, and executed from the top
level as well.

Accessing the same module both from within a package and outside it
may seem like a bad idea, and in many ways, it is. You may get a
double import of the same module with subtle, mysterious bugs to
follow, when e.g. you suddenly have two copies of the "same" class,
and isinstance(obj,mymodule.Cls) fails unexpectedly.

But it's quite common all the same: The
if __name__ == "__main__":
idiom is often used, even within packages. But that is currently
incompatible with using relative imports. It seems to me that unless
we rethink the main idiom competely (which may not be a bad idea by
the way, for the reasons given above), relative imports at the top
level will need to be allowed.

Another addition I'd like to see it the "import .foo" form. Currently
only "from"-imports have a relative form. The argument against is
that "import X" binds the name X, and it's not clear which name the
relative import binds.

I move that it's blindingly obvious: "import .foo" binds "foo",
equivalent to "from . import foo". Did anyone really expect the name
".foo" to be bound?

It's not a big deal though, as you only need to type "from ." once per
module anyway. Using another improvement in 2.5, you can now write:

from . import (

- Anders
Sep 23 '06 #1
0 1278

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by GrayGeek | last post: by
1 post views Thread by Alexey Borzenkov | last post: by
12 posts views Thread by Alan Isaac | last post: by
5 posts views Thread by jm.suresh | last post: by
reply views Thread by Alan Isaac | last post: by
reply views Thread by Kay Schluehr | last post: by
1 post views Thread by Waqarahmed | last post: by
reply views Thread by Salome Sato | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.