Reputation: 1360
I'm using Python 3 with Django and I try to make cross imports which fails and I don't know why... Here is the structure:
|--my_project
|-- system
|--__init__.py
|-- a.py
|-- b.py
a.py
from .b import TestB
class TestA(object):
pass
b.py
from .a import TestA
class TestB(object):
pass
The import in a.py works. But the one in b.py doesn't work: ImportError: cannot import name 'TestA'
. I also tried using absolute path (from myproject.system.a import TestA
but with no luck).
Any idea about the problem?
Upvotes: 0
Views: 1318
Reputation: 149776
There're several approaches you can use to address the cross-imports problem:
Re-organize your modules so that there're no cross-imports, i.e. put the classes to a single module, etc.
Replace from module import foo
with import module
and use full names.
Put imports at the end of modules (not recommended).
See also Circular imports in Python.
Upvotes: 1
Reputation: 22021
Putting imports at the end of your a.py and b.py should fix issues. If it doesn't help you try to move import into class definition block, so replace
from .a import TestA
Class TestB(object):
pass
to
Class TestB(object):
from .a import TestA
pass
Small Suggestion: do not use relative imports.
Upvotes: 0