1

The answers to this question have led me to believe that circular imports of modules should work, but I am running into trouble with the following package:

File structure:

my_package
--| my_package
    |-- __init__.py
    |-- mod1.py
    |-- mod2.py
--| setup.py

__init__.py:

from . import mod1, mod2

mod1.py:

from . import mod2

mod2.py:

from . import mod1

Trying to import the package gives the error:

ImportError: cannot import name 'mod1'

What can I do to make these imports work?

Community
  • 1
  • 1
C_Z_
  • 7,427
  • 5
  • 44
  • 81
  • Did you check the second answer? (I strongly recommend restructuring your program to avoid circular imports, though.) – user2357112 May 09 '16 at 18:36
  • Python usually will not allow circular references as it will prevent certain garbage collectors from firing and create memory leaks. A good break down of why http://engineering.hearsaysocial.com/2013/06/16/circular-references-in-python/ – Eric Thomas May 09 '16 at 18:38
  • I find that usually if you design your structure well, you never need circular dependencies. If mod1 needs stuff from mod2 and vice versa, put the common stuff in a third module, or join the modules. – L3viathan May 09 '16 at 19:00
  • 1
    @EricThomas: No, circular references are completely permitted. They even changed the `__del__` semantics in recent versions to prevent the memory leak case. – user2357112 May 09 '16 at 20:09

0 Answers0