[Twisted-Python] cleanup in twisted

Jp Calderone exarkun at divmod.com
Wed May 25 09:27:27 EDT 2005


On Wed, 25 May 2005 06:12:16 -0700 (PDT), Joachim Boomberschloss <boomberschloss at yahoo.com> wrote:
>
>--- Jp Calderone <exarkun at divmod.com> wrote:
>
>> [snip]
>>
>> Rescuing an object from garbage collection is easier
>> than you may expect:
>>
>>   exarkun at boson:~$ python
>>   Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
>>   [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
>>   Type "help", "copyright", "credits" or "license"
>> for more information.
>>   >>> L = []
>>   >>> class Foo:
>>   ...     def __del__(self):
>>   ...             L.append(self)
>>   ...
>>   >>> f = Foo()
>>   >>> del f
>>   >>> L
>>   [<__main__.Foo instance at 0xb7dff34c>]
>>   >>>
>>
>> Of course, for it to ever be collected, you'll need
>> to take it out of that list.
>>
>
>Hmmm. Good to know. I thought this sort of thing was
>considered illegal in Python. This resolves deferring
>the destruction, but not the problem with reference
>cycles. Is there any way to do it without __del__?

The garbage collector goes to great lengths to make sure it works :)

Well, here's an example of how you'd use weakrefs.  It may or may not apply to your case:

  exarkun at boson:~$ python
  Python 2.4.1 (#2, Mar 30 2005, 21:51:10) 
  [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
  Type "help", "copyright", "credits" or "license" for more information.
  >>> import weakref
  >>> def cleanup(handle):
  ...     print 'Cleaned up', handle
  ... 
  >>> class Foo:
  ...     def __init__(self, x, y, z):
  ...         self.x, self.y, self.z = x, y, z
  ...         self._cleanup = weakref.ref(
  ...             self, lambda deadref: cleanup(x))
  ... 
  >>> f = Foo('hello', 'world', 42)
  >>> del f
  Cleaned up hello
  >>> 

The main point here is the isolation of the objects needed for actual cleanup from the object which may participate in a cycle. In this way, it is similar to moving the __del__ implementation onto a separate class.

Since the cleanup callback does not have access to the instance, it is somewhat more limited.  For example, if the `x' attribute of a Foo instance is ever changed, the callback will still be invoked with the original value.

Jp




More information about the Twisted-Python mailing list