Note that there are some explanatory texts on larger screens.

plurals
  1. POBase class deleted before subclass during python __del__ processing
    primarykey
    data
    text
    <p><strong>Context</strong></p> <p>I am aware that if I ask a question about Python destructors, the standard argument will be to use contexts instead. Let me start by explaining why I am not doing that.</p> <p>I am writing a subclass to <code>logging.Handler</code>. When an instance is closed, it posts a sentinel value to a Queue.Queue. If it doesn't, a second thread will be left running forever, waiting for Queue.Queue.get() to complete.</p> <p>I am writing this with other developers in mind, so I don't want a failure to call close() on a handler object to cause the program to hang.</p> <p>Therefore, I am adding a check in __del__() to ensure the object was closed properly.</p> <p>I understand circular references may cause it to fail in some circumstances. There's not a lot I can do about that.</p> <p><strong>Problem</strong></p> <p>Here is some simple example code:</p> <pre><code>explicit_delete = True class Base: def __del__(self): print "Base class cleaning up." class Sub(Base): def __del__(self): print "Sub-class cleaning up." Base.__del__(self) x = Sub() if explicit_delete: del x print "End of thread" </code></pre> <p>When I run this I get, as expected:</p> <pre><code>Sub-class cleaning up. Base class cleaning up. End of thread </code></pre> <p>If I set <code>explicit_delete</code> to <code>False</code> in the first line, I get:</p> <pre><code>End of thread Sub-class cleaning up. Exception AttributeError: "'NoneType' object has no attribute '__del__'" in &lt;bound method Sub.__del__ of &lt;__main__.Sub instance at 0x00F0B698&gt;&gt; ignored </code></pre> <p>It seems the definition of Base is removed before the <code>x.__del__()</code> is called.</p> <p>The Python Documentation on __del__() warns that the subclass needs to call the base-class to get a clean deletion, but here that appears to be impossible.</p> <p>Can you see where I made a bad step?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload