Circular dependency in Python Circular dependency in Python python python

Circular dependency in Python


Importing Python Modules is a great article that explains circular imports in Python.

The easiest way to fix this is to move the path import to the end of the node module.


One other approach is importing one of the two modules only in the function where you need it in the other. Sure, this works best if you only need it in one or a small number of functions:

# in node.py from path import Pathclass Node     ...# in path.pyclass Path  def method_needs_node():     from node import Node    n = Node()    ...


I prefer to break a circular dependency by declaring one of the dependencies in the constructor of the other dependent class. In my view this keeps the code neater, and gives easy access to all methods who require the dependency.

So in my case I have a CustomerService and a UserService who depend on each other. I break the circular dependency as follows:

class UserService:    def __init__(self):        # Declared in constructor to avoid circular dependency        from server.portal.services.admin.customer_service import CustomerService        self.customer_service = CustomerService()    def create_user(self, customer_id: int) -> User:        # Now easy to access the dependency from any method        customer = self.customer_service.get_by_id(customer_id)