title: Python Pickle Module and OOP
body: <p>In the example below <code>pickle</code> crashes with every attempt to save an instance A to file. </p>
  
  <p>Why does it happen? </p>
  
  <p>How to avoid it? </p>
  
  <p>How to get around it?</p>
  
  <pre><code>class Base(dict):
      def __init__(self):
          super(Base, self).__init__()
  
  class ClassA(Base):
      def __init__(self):
          super(ClassA, self).__init__()  
      def setInstB(self, instB):
          self['instB']=instB
  
  class ClassB(Base):
      def __init__(self):
          super(ClassB, self).__init__()
      def setInstA(self, instA):
          self['instA']=instA
  
  instA=ClassA()
  instB=ClassB()
  
  instA.setInstB(instB)
  instB.setInstA(instA)
  
  import pickle
  pickle.dump( instA, open( "save.p", "wb" ) )
  </code></pre>
  
  <h2>Posted later.</h2>
  
  <p>If <code>Base(dict)</code> class is not declared to be a subclass of built-in <code>dict</code> the problem goes away. Running the code posted below raises no <code>pickle</code> errors. But I still want to know why pickle fails and how to make it work with Classes inheriting from <code>dict</code>.</p>
  
  <pre><code>class Base(object):
      def __init__(self):
          super(Base, self).__init__()
  
  class ClassA(Base):
      def __init__(self):
          super(ClassA, self).__init__()  
      def setInstB(self, instB):
          self.instB=instB
  
  class ClassB(Base):
      def __init__(self):
          super(ClassB, self).__init__()
      def setInstA(self, instA):
          self.instA=instA
  
  instA=ClassA()
  instB=ClassB()
  
  instA.setInstB(instB)
  instB.setInstA(instA)
  
  import pickle
  pickle.dump( instA, open( "save.p", "wb" ) )
  </code></pre>