weak reference to bound method

Ole Streicher ole-usenet-spam at gmx.net
Fri Oct 2 11:20:19 EDT 2009


Hi Peter,

Peter Otten <__peter__ at web.de> writes:
>>>> I am a bit surprised that already such a simple problem is virtually
>>>> unsolvable in python. 

> Btw, have you implemented such a design in another language?

No. 

> I think I'd go for a simpler approach, manage the lifetime of MyClass 
> instances manually and add a MyClass.close() method that sets a flag which 
> in turn is periodically read by DoAsync() and will eventually make it stop.

Has the disadvantage that I rely on the user. We already have a garbage
collector, so why not use it? It is exactly made for what I want: delete
unused objects.

The solution I have now is still untested, but maybe the separation of
the thread will work:
------------------------------<8----------------------------
import threading
import weakref

class AsyncThread(threading.Thread):
    def __init__(self, func):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self._cond = threading.Condition()
        self._func = weakref.ref(func, self.run)
        self.start()

    def run(self):
        while self._func():
            with self._cond:
                while not self.scheduled:
                    self._cond.wait()
                self.scheduled = False
            self._func()
            func = self._func()
            if func:
                func()

    def __call__(self):
        with self._cond:
            self.scheduled = True
            self._cond.notify()

class DoAsync(object):
    def __init__(self, func):
        self._func = func
        self._thread = AsyncThread(self._func)

    def __call__(self):
        self._thread()
------------------------------<8----------------------------

The AsyncThread has now no reference that could prevent the referenced
from the GC. And the function is always stored in the DoAsync object and
will be only collected if this is removed (what is the case if the
parent object is being deleted)

Regards

Ole



More information about the Python-list mailing list