Relative import first impressions

Anders J. Munch 2006 at jmunch.dk
Sat Sep 23 17:18:01 CEST 2006


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 (
     this,
     that,
     )

- Anders



More information about the Python-list mailing list