Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>About the only reason you should ever use <code>__del__</code> is to help the garbage collector collect more garbage. For instance, if you are implementing something like the <code>ctypes</code> module that attaches shared libraries to the running process, it makes sense to unload those libraries when the last reference to it is collected, to allow its address space to be used for something else.</p> <p>For managing <em>other</em> kinds of resources, you almost certainly don't want to have anything to do with the garbage collector. The correct tool for this is <a href="http://docs.python.org/reference/datamodel.html#with-statement-context-managers" rel="noreferrer">context managers</a>. Unlike languages such as C++ or Ada where variable scope is used for RAII, python uses the <code>with</code> statement, along with an object that has an <code>__enter__</code> and <code>__exit__</code> method. Many built in python types use this exact mechanism to make sure finalization steps actually occur:</p> <pre><code>&gt;&gt;&gt; x = file("foo", 'w') &gt;&gt;&gt; x.closed False &gt;&gt;&gt; with x: ... x.write("bar") ... &gt;&gt;&gt; x.closed True </code></pre> <p>This is also valuable from the point of view of the zen of python:</p> <blockquote> <p>Explicit is better than implicit.</p> </blockquote> <p>because it is clear that cleanup is occuring, it is explicitly written that way. This is much better than the case of cleanup happening "magically" when some hidden variable (the reference count, if one exists, and it doesn't in PyPy or IronPython or Jython) reaches some particular value, maybe.</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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