Search code examples
pythonreference-countingdel

Behaviour of __del__ on unassigned python object


First ever question, sorry if it's been asked before - I did search but I couldn't find anything that seemed to answer it.

I have been trying to understand the behaviour of python's __del__ method, as I need it to perform some cleanup on wrapped C code.

My understanding of __del__ is that is is called when an object's reference count reaches zero, not when del is called on an object reference. This led me to believe that instantiating an object without assignment would call __init__ then __del__ immediately after, but this doesn't seem to be the case, as the following code demonstrates:

class Foo():
   def __init__(self):
      print "Hello"
   def __del__(self):
      print "Goodbye"

Foo()
Hello
<__main__.Foo instance at 0x7fb943075a28>

Can anyone explain what's going on here? Thanks in advance.


Solution

  • The Python interactive interpreter keeps a reference to the last result in the _ variable. Your object is still alive.

    Run another expression to clear it:

    >>> class Foo():
    ...    def __init__(self):
    ...       print "Hello"
    ...    def __del__(self):
    ...       print "Goodbye"
    ... 
    >>> Foo()
    Hello
    <__main__.Foo instance at 0x100651ef0>
    >>> _
    <__main__.Foo instance at 0x100651ef0>
    >>> 'Hello world!'
    Goodbye
    'Hello world!'