Mutual interdependency problem

Jeremy Sanders jeremy+complangpython at jeremysanders.net
Wed Jun 7 15:10:15 EDT 2006


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 do
>>> import importproblem.dir1
Traceback (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

-- 
Jeremy Sanders
http://www.jeremysanders.net/



More information about the Python-list mailing list