Resolve circular reference

Carl Banks pavlovevidence at gmail.com
Mon Jan 10 10:20:06 EST 2011


On Jan 10, 12:21 am, moerchendiser2k3 <googler.
1.webmas... at spamgourmet.com> wrote:
> so there is no chance without using weakrefs?
> any ideas, tips, workarounds how I might handle this?

No, sorry: as long as a reference to an object exists, the object is
never deleted.  There is no way to get around this.

Python in general isn't designed to allow for exact control over the
destruction of objects.  Even in CPython, which uses reference
counting, there are a bunch of situations where a reference might be
stored to an object that keeps it alive.  (Unexpected locations where
a stray reference might exist: an unpickler object, the _ symbol in
the interactive shell.)  Other implementations, like Jython and
IronPython, don't use reference counting and don't provide for any
particular time at all for an object to be destroyed.

The recommended way to ensure timely release of resources in Python is
to provide a method (such as close or finalize) to explicity release
the resource--the object then lives on in a zombie state.  The with
statement can be used in many cases to avoid the need to call this
method explicitly.  For example, if you were to run this code in
Python:

    with open(filename) as f:
        g = f
    print g

It would print <closed file 'whatever' ...>.  The object still exists
because there is a reference to it, but the file has been closed.


If you can tell us why it's so important that the object be destroyed
at that given time, even while a reference to it exists, maybe we can
give you better suggestions.


Carl Banks



More information about the Python-list mailing list