Mutual interdependency problem

J

Jeremy Sanders

I'm getting problems with modules with interdependencies when using the
import form "import foo.bar as bar".

Here are a set of files which replicate the problem

::::::::::::::
importproblem/__init__.py
::::::::::::::
# This is blank

::::::::::::::
importproblem/dir1/__init__.py
::::::::::::::
from bar import *

::::::::::::::
importproblem/dir1/bar.py
::::::::::::::
import importproblem.dir2 as foo
def hello():
print "Hello world"

::::::::::::::
importproblem/dir2/__init__.py
::::::::::::::
from foo import *

::::::::::::::
importproblem/dir2/test.py
::::::::::::::
import importproblem.dir1.bar as bar
def hello():
print "Hello world"

::::::::::::::
importproblem/dir2/foo.py
::::::::::::::
import importproblem.dir1 as dir1
def hello():
print "Hello world"

If you now doTraceback (most recent call last):
File "<stdin>", line 1, in ?
File "importproblem/dir1/__init__.py", line 1, in ?
from bar import *
File "importproblem/dir1/bar.py", line 1, in ?
import importproblem.dir2 as foo
File "importproblem/dir2/__init__.py", line 1, in ?
from foo import *
File "importproblem/dir2/foo.py", line 1, in ?
import importproblem.dir1 as dir1
AttributeError: 'module' object has no attribute 'dir1'

[GCC 4.1.0 20060210 (Red Hat 4.1.0-0.24)]

If you remove the "as dir1" from the import line in dir2/foo.py then this
works. Can this be explained or fixed?

Maybe the "from foo import *" style in __init__.py is a bad idea, but it
allows you to expose a flat namespace without having to put all the code
into one file. Then naturally you need mutual interdependencies, and then
it breaks! I can work around it by removing the "as XXX" parts on the
import statement, but it gets annoying having to specify the full path.

Jeremy
 
A

AdSR

Jeremy said:
I'm getting problems with modules with interdependencies when using the
import form "import foo.bar as bar".

[snip]

Maybe the "from foo import *" style in __init__.py is a bad idea, but it
allows you to expose a flat namespace without having to put all the code
into one file. Then naturally you need mutual interdependencies, and then
it breaks! I can work around it by removing the "as XXX" parts on the
import statement, but it gets annoying having to specify the full path.

What worries me is that you have two modules that import each other.
Are you sure you can't do it any other way?

AdSR
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top