title: Python: deletion of self referencing object
body: <p>I want to ask how to delete <strong>an object with a self-reference</strong> in Python.</p>
  
  <p>Let's think a class, which is a simple example to know when it is created and when it is deleted:</p>
  
  <pre><code>#!/usr/bin/python
  class TTest:
    def __init__(self):
      self.sub_func= None
      print 'Created',self
    def __del__(self):
      self.sub_func= None
      print 'Deleted',self
    def Print(self):
      print 'Print',self
  </code></pre>
  
  <p>This class has a variable self.sub_func to which we assume to assign a function.  I want to assign a <strong>function using an instance of TTest</strong> to self.sub_func.  See the following case:</p>
  
  <pre><code>def SubFunc1(t):
    t.Print()
  def DefineObj1():
    t= TTest()
    t.sub_func= lambda: SubFunc1(t)
    return t
  
  t= DefineObj1()
  t.sub_func()
  del t
  </code></pre>
  
  <p>The result is:</p>
  
  <pre><code>Created &lt;__main__.TTest instance at 0x7ffbabceee60&gt;
  Print &lt;__main__.TTest instance at 0x7ffbabceee60&gt;
  </code></pre>
  
  <p>that is to say, <strong>though we executed "del t", t was not deleted</strong>.</p>
  
  <p>I guess the reason is that t.sub_func is a self-referencing object, so reference counter of t does not become zero at "del t", thus t is not deleted by the garbage collector.</p>
  
  <p>To solve this problem, I need to insert</p>
  
  <pre><code>t.sub_func= None
  </code></pre>
  
  <p>before "del t"; in this time, the output is:</p>
  
  <pre><code>Created &lt;__main__.TTest instance at 0x7fab9ece2e60&gt;
  Print &lt;__main__.TTest instance at 0x7fab9ece2e60&gt;
  Deleted &lt;__main__.TTest instance at 0x7fab9ece2e60&gt;
  </code></pre>
  
  <p>But this is strange.  <strong>t.sub_func is part of t, so I do not want to care about clearing t.sub_func when deleting t</strong>.</p>
  
  <p>Could you tell me if you know a good solution?</p>