[Python-Dev] intra-package mutual imports fail: "from <pkg> import <mod>"

David Goodger goodger@users.sourceforge.net
Sun, 02 Jun 2002 10:11:31 -0400


I wrote:
>> module5.py:
>> from package import module6   # absolute import
>> 
>> module6.py:
>> from package import module5
>> [...]
>> ImportError: cannot import name module5
>> 
>> Is this behavior expected?  Or is it a bug?

Matthias Urlichs replied:
> The problem is that importing with from consists of two steps:
> - load the module
> - add the imported names to the local namespace
> 
> Since this addition is by reference to the actual object and not to
> the symbol's name in the other module, a concept which Python doesn't
> have (use Perl if you want this...), your recursive import doesn't
> work.
> 
> The solution would be:
>  import package.module6 as module6
> 
> which should have the same effect.

Perhaps I'm just dense, or perhaps it's because of my choice of names
in my example, but I don't understand the explanation.  Could you be
more specific, perhaps with a concrete example?  Despite Guido's
"Good explanation!", the above text in the FAQ entry wouldn't
eliminate my confusion.  I suspect it's a good explanation for those
that already understand what's going on behind the scenes.

-- 
David Goodger  <goodger@users.sourceforge.net>  Open-source projects:
  - Python Docutils: http://docutils.sourceforge.net/
    (includes reStructuredText: http://docutils.sf.net/rst.html)
  - The Go Tools Project: http://gotools.sourceforge.net/