relative imports with the __import__ function

Peter Otten __peter__ at web.de
Thu Dec 10 05:24:04 EST 2009


Chris Colbert wrote:

> It seems the relative import level is dependent on the location of the
> main entry module. I thought the whole idea of relative imports was to
> make the import independent of the entry point?

You don't have to specify it explicitly, so you can move a module containing

from .foo import bar

into another package without changing its source code (provided there is a 
foo submodule with a bar attribute). This includes the trivial case of 
renaming the parent package.

Of course Python has to know the importing module's location, just like you 
cannot meet me one block north and three blocks west unless you know where I 
currently am.

See also

http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports

Peter



More information about the Python-list mailing list