dhruvg dhruvg - 3 months ago 14
Python Question

How to refactor this to avoid a circular dependency?

I have the following setup:

# generator.py
from node import Node

class Generator(object):
@staticmethod
def generate(self, node):
return [Node(), Node(), Node()]

# node.py
from generator import Generator

class Node(object):
def generate_child_nodes(self):
self.child_nodes = Generator.generate(self)


This over-simplified setup is causing a circular dependency issue.

I generally want the ability of a class to create instances of itself (ex. for mimic-ing a parent child relationship) using a different module (generator.py in this case).

Answer

Like this:

# generator.py

class Generator(object):
  @staticmethod
  def generate(self, node):
     from node import Node
     return [Node(), Node(), Node()]

# node.py
from generator import Generator

class Node(object):
   def generate_child_nodes(self):
     self.child_nodes = Generator.generate(self)