title: Pickling a graph with cycles
body: <p>I have a custom node class in python that is built into a graph (which is a dictionary). Since these take a while to create, I'd like to pickle them so that I don't have to reconstruct them everytime I run my code.</p>
  
  <p>Unfortunately, because this graph has cycles, cPickle hits the maximum recursion depth:</p>
  
  <blockquote>
    <p>RuntimeError: maximum recursion depth exceeded while pickling an object</p>
  </blockquote>
  
  <p>This is my node object:</p>
  
  <pre><code>class Node:
      def __init__(self, name):
          self.name = name
          self.uid = 0
          self.parents = set()
          self.children = set()
  
      def __hash__(self):
          return hash(self.name)
  
      def __eq__(self, that):
          return self.name == that.name
  
      def __str__(self):
          return "\n".join(["Name: " + self.name,
                            "\tChildren:" + ", ".join([c.name for c in self.children]),
                            "\tParents:" + ", ".join([p.name for p in self.parents])
                            ]
                           )
  </code></pre>
  
  <p>This is how I build my graph:</p>
  
  <pre><code>def buildGraph(input):
      graph = {}
      idToNode = {}
  
      for line in input:
          ## Input from text line by line looks like
          ## source.node -&gt; target.node
          source, arr, target = line.split()
          if source in graph:
              nsource = graph[source]
          else:
              nsource = Node(source)
              nsource.uid = len(graph)
              graph[source] = nsource
              idToNode[nsource.uid] = nsource
  
          if target in graph:
              ntarget = graph[target]
          else:
              ntarget = Node(target)
              ntarget.uid = len(graph)
              graph[target] = ntarget
              idToNode[ntarget.uid] = ntarget
  
          nsource.children.add(ntarget)
          ntarget.parents.add(nsource)
      return graph
  </code></pre>
  
  <p>Then in my main, I have</p>
  
  <pre><code>    graph = buildGraph(input_file)
      bo = cPickle.dumps(graph)
  </code></pre>
  
  <p>and the second line is where I get my recursion depth error.</p>
  
  <p>Are there any solutions outside of changing the structure of Node?</p>