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

Matthias Urlichs smurf@noris.de
Sun, 2 Jun 2002 16:44:07 +0200


Hi,

David Goodger:
> 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? 

foo.py: from bar import one
bar.py: from foo import two
main.py: import foo

So what happens is, more or less:

main imports foo
  Empty globals for foo are created
  foo is compiled
  foo loads bar
    Empty globals for bar are created
    bar is compiled
    bar loads foo (which is a no-op since there already is a module named foo)
    bar.two = foo.two
      ... which fails, because the compiler isn't done with foo yet and the
      global symbol dict for foo is still empty.

> eliminate my confusion.  I suspect it's a good explanation for those
> that already understand what's going on behind the scenes.
> 
_If_ you can change foo.py so that it reads:

two = 2
from bar import one

i.e., initialize the exports first and load afterwards, the test
would work. However, the following will NOT work:

two = None
from bar import one
two = do_something(with(bar.one))

for (hopefully) obvious reasons.

-- 
Matthias Urlichs     |     noris network AG     |     http://smurf.noris.de/