How do we handle circular dependency between Python classes?

PythonServer Side ProgrammingProgramming

We have the following code which shows circular dependency between the python classes.

class P():
     q = Q().do_something();
     def do_something(self):
 class Q():
     p = P().do_something();
     def do_something(self):

In case of classes, unlike with functions, the body of a class is executed at definition time. To define class P, we need to actually call a Q method, which we can't do because class Q isn't defined yet.

To work around this, we can define the classes and then add the properties afterward −

class P(object):
class Q(object):
P.q = Q.do_something()
Q.p = P.do_something()

If each do_something call relies on the other call already having been executed, this won't work. We still need to perform more changes to fix the problem.

Classes have these problems because directives on the class level (q = Q.do_something()) are executed while defining the class, not when you create an instance of the class

We may complete the definition of a class later, after both classes are defined. This proves the point that Python is a dynamic language..

Updated on 15-Jun-2020 11:56:56