Cyclic module dependencies and relative imports in Python

Viewed 6121

Suppose we have two modules with cyclic dependencies:

# a.py
import b
def f(): return b.y
x = 42

# b.py
import a
def g(): return a.x
y = 43

The two modules are in the directory pkg with an empty __init__.py. Importing pkg.a or pkg.b works fine, as explained in this answer. If I change the imports to relative imports

from . import b

I get an ImportError when trying to import one of the modules:

>>> import pkg.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/a.py", line 1, in <module>
    from . import b
  File "pkg/b.py", line 1, in <module>
    from . import a
ImportError: cannot import name a

Why do I get this error? Isn't the situation pretty much the same as above? (Is this related to this question?)

Edit: This question is not about software design. I'm aware of ways to avoid the circular dependency, but I'm interested in the reason for the error anyway.

3 Answers
Related