Problem with python 3.2 and circular imports

Frank Millman frank at chagford.com
Sun Feb 27 05:08:12 EST 2011


Hi all

I thought I was getting the hang of circular imports, but after upgrading to 
python 3.2 I am stumped again. I know some people think that circular 
imports are always bad, but others suggest that, provided you understand the 
potential problems, they can be acceptable.

Assume the following structure -

main.py
/pkg
    __init__.py
    mod1.py
    mod2.py

main.py
    from pkg import mod1

mod1.py
    import mod2

mod2.py
  import mod1

Using python 2.6, running main.py works.

After running 2to3.py on the above directory, mod1.py was changed to 'from . 
import mod2' and mod2.py was changed to 'from . import mod1'.

With python 3.2, it now fails with the following traceback -

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from pkg import mod1
  File "pkg\mod1.py", line 1, in <module>
    from . import mod2
  File "pkg\mod2.py", line 1, in <module>
    from . import mod1
ImportError: cannot import name mod1

I have read the relevant peps and various other material, understood them to 
a certain extent, tried several alternatives, but could not find a solution.

I have found a hack that works, but I don't like it very much. I added the 
following to '__init__.py' -
  import os
  import sys
  sys.path.insert(0, os.path.dirname(__file__))

This adds the package name into the search path.

Then I changed mod1.py and mod2.py back to the original 'import mod2' and 
'import mod1'.

It works, but it seems to be defeating the purpose of PEP 328, which I 
thought was an improvement.

Any comments or suggestions will be appreciated.

Frank Millman





More information about the Python-list mailing list