0

I have a circular dependency problem. In the direction /path/to/src, there are 2 files a.py and b.py.

In a.py, there is a

from . import b

and in b.py, there is a

from . import a

So there's a circular dependency. Based on How to avoid circular imports in Python?, one way to resolve this is to use absolute imports, so I tried

In a.py:

import path.to.src.b as b

and in b.py, there is a

import path.to.src.a as a

But I still get the circular dependency error during execution

module 'path.to.src.a' has no attribute 'b'
24n8
  • 1,898
  • 1
  • 12
  • 25
  • What Python version are you using? The `as` can cause problems on some Python versions, but they added a kludge back in 3.7 or something that should handle this case. – user2357112 May 25 '23 at 13:52
  • 1
    Read the answer you linked all the way to the end. Absolute imports is the solution to case 1. What you are seeing is case 2, an actual circular dependancy you need to somehow refactor out. – matszwecja May 25 '23 at 13:54
  • The linked answer mentions that that solution is for fixing circular import dependencies that don't involve circular references . I.e., `a` imports `b` which imports `a`, but `b` doesn't try to reference any attributes of `a` at import time. – Brian61354270 May 25 '23 at 13:56
  • @user2357112 In this particular case I was using 3.7, but I also need to support python2 – 24n8 May 25 '23 at 13:57
  • Import the dependency inside the function where you need it; not at the module level. – 9769953 May 25 '23 at 13:59
  • @matszwecja Oh actually i only previously read the accepted answer. You are referring to Brendan's answer right? – 24n8 May 25 '23 at 14:03
  • @24n8 yes, the most upvoted one. – matszwecja May 25 '23 at 14:07
  • @9769953 yeah I am aware of that solution. I know this is silly, but what if there was a poorly designed inheritance case that caused this, where, a derived class inherits a base, but the but the base class has a dependency on the child class due to the poor design? where would the imports occur in such a case – 24n8 May 25 '23 at 14:10
  • Well, if people are going to father their own mother, then all time-travel hell will break loose and the Universe probably collapses in on itself. In such a specific bad case, I don't think handling circular imports helps; something more fundamental should really be resolved. – 9769953 May 25 '23 at 14:29

0 Answers0