gc questions

Jeremy Hylton jeremy at zope.com
Wed Jun 18 17:27:26 CEST 2003

On Wed, 2003-06-18 at 07:39, Edward K. Ream wrote:
> I have several questions about gc:
> 1.  The gc documentation says: " This module...provides access to
> unreachable objects that the collector found but cannot free."  I thought
> the gc could free cycles.  Why would the gc be unable to free objects that
> are, in fact, no longer being used?

A cycle of unreachable objects where one or more of the objects has a
finalizer is uncollectable.  The garbage collector can't know which
__del__ method to call first, if, in fact, it's safe to call any of them

I believe the garbage collector could call an __del__ for cycles
involving only a single finalizer, but it doesn't.

> 2. What do the terms "collectable" and "uncollectable" garbage mean?  The gc
> will show such objects when gc.set_debug(gc.DEBUG_STATS) is in effect.

See answer above.

> 3.  I have not been able to do anything with gc.get_objects() except get its
> length.  For example, the following throws an exception:

I'm surprised that you have a problem.  I've used it without any

> global lastObjectList
> gc.disable()
> objects = gc.get_objects()[:]  # omitting [:] also fails.
> gc.enable()

I'm surprised that you call gc.disable() and gc.enable() here.  There's
very little chance that a collection will occur as a result of calling
get_objects().  Even if it does occur, what's the problem?

I also don't understand why you make a copy of the list?  It's probably
a very big list and I don't see any need to duplicate it.

> if lastObjectList:
>             for o in objects: # This can fail!
>                         if o not in lastObjectList:
>                                     print id(o)
> lastObjectList = objects
> The exception is thrown at the statement "for o in objects:" and the
> exception is a unicode error!
> Is there anything obviously wrong in this example? Being able to see which
> objects have just been added to the get_objects() list would be most
> helpful.

Are you sure there error isn't on the "o not in lastObjectList" line? 
If you have a Unicode string and a regular string containing non-ASCII
characters, you'll get a UnicodeError when you try to compare them.

Are you sure you want to do a quadratic time algorithm for this?  You're
doing a compare on every object in lastObjectList every time through the
for loop.

You might also be interested to try sys.getobjects(), which is only
available in a debug build of Python.  It returns all objects, not just
those involved in garbage collection.


More information about the Python-list mailing list