[Tutor] Object Destruction

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 25 Jan 2001 09:35:03 +0100


On Wed, Jan 24, 2001 at 10:34:05PM -0800, Danny Yoo wrote:
> On Wed, 24 Jan 2001, Gregg T. Geiger wrote:
> 
> > What are scope rules for class objects and when are they
> > destroyed, specifically with regards to for loops?
> > 
> > That is, if a class Spam is defined somewhere and used in a
> > for loop as follows:
> > 
> > for i in [0, 1, 2, 3, 4]:
> >   spam = Spam()
> >   # end of for loop
> 
> Hmm... Python is reference garbage collected, so whenever an instance's
> reference count goes to zero, the instance should implode. We can
> experimentally test to see when an object gets garbage collected by
> overriding the '__del__' method.  Since Python works well with the
> interpreter, let's try it out:
> 
> ###
> >>> class TestDel:
> ...     def __init__(self, name):
> ...         self.name = name
> ...     def __del__(self):
> ...         print self.name, "garbage collected"
> ... 
> >>> TestDel("Anna")
> <__main__.TestDel instance at 0x81ca2fc>  
> 
> # that's curious, I expected garbage collection at this point... Strange!
> # I'll have to think about that one later...

Things like this can be surprising in the interactive interpreter. It keeps
a reference to the last result, try
>>> _
<___main___.TestDel instance at 0x81ca2fc>
>>> 3
Anna garbage collected
3

 
> >>> x = TestDel("Anna")
> >>> del(x)
> Anna garbage collected
> >>> x = TestDel("Anna")
> >>> x = TestDel("King")
> Anna garbage collected
> >>> for i in range(5):
> ...     x = TestDel(i)
> ... 
> King garbage collected
> 0 garbage collected
> 1 garbage collected
> 2 garbage collected
> 3 garbage collected
> ###
> 
> So it pretty much does what you'd expect... except for that odd thing at
> the very beginning.  Weird!

Apparently none of the things later return a result that the interpreter
keeps as _...

> > will an object be created and destroyed with each pass
> > through the loop or does each instance remain "alive"?  In
> > a comparable C++ loop
> 
> From the results above, yes.

The objects will be destroyed, *unless* they initialize some things in their
__init__, and those things still keep references back to the object.

-- 
Remco Gerlich