weak reference to bound method

Ole Streicher ole-usenet-spam at gmx.net
Fri Oct 2 05:55:56 EDT 2009


Hello Peter,

Peter Otten <__peter__ at web.de> writes:
> Is there an actual use case?

I discussed this in the german newsgroup. Here is the use in my class:
-----------------------------8<-----------------------
import threading
import weakref

class DoAsync(threading.Thread):
    def __init__(self, func):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self._cond = threading.Condition()
        self.scheduled = False
        self._func = weakref.ref(func, self._cleanup)
        self.start()

    def run(self):
        while self._func():
            with self._cond:
                while not self.scheduled and self._func():
                    self._cond.wait()
                self.scheduled = False
            func = self._func()
            if func:
                func()
                    
    def __call__(self):
        with self._cond:
            self.scheduled = True
            self._cond.notify()
        
    def _cleanup(self, ref):
        self()
-----------------------------8<-----------------------

The use for this callable class is to take a function call, and whenever
the DoAsync object is called, trigger a call to the stored function.

Other classes use it like:

-----------------------------8<-----------------------
class MyClass:
    def __init__(self):
         ...
         self.update = DoAsync(self._do_update)

    def _do_update(self):
         do_something_that_takes_long_and_shall_be_done_after_an_update()
-----------------------------8<-----------------------

Since DoAsync starts its own thread, I get a classical deadlock
situation: DoAsync needs a reference to the method to be called, and as
long as the thread is running, the MyClass object (which contains the
method) cannot be cleaned up. This would be a classic case for a weak
reference, if Python would not create it at calling time.

> No. o.myfunc is a different object, a bound method, and every time you 
> access o's myfunc attribute a new bound method is created:

What is the reason for that behaviour? It looks quite silly to me.

And how can I get a reference to a bound method that lives as long as
the method itself?

Regards

Ole



More information about the Python-list mailing list