1

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.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
2birds
  • 13
  • 2

1 Answers1

5

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!'
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks very much! Sneaky interpreter, hoarding references! – 2birds Oct 09 '14 at 10:57
  • @MartijnPieters Done. I've been lurking on this site for years, never needed to ask a question until today. I need to learn how to use it now! – 2birds Oct 09 '14 at 13:14