weak references and threads

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Apr 25 04:42:16 EDT 2002


Philip Swartzleonard <starx at pacbell.net> wrote in
news:Xns91FA17D7E4F8ARASXnewsDFE1 at 130.133.1.4: 

> There is only one reason I know that you would want to use weak 
> references, and that is in the creation of advanced, customized data 
> structures. The point is to avoid something called 'circular
> references', which is probably best explained by an example. Let's
> take a realy basic class (this is right from my 2.2 IDLE prompt):
> 
I have used weak references to quite nice effect in some of my unit tests. 
The idea is that I create a weak value dictionary: that is a dictionary 
where the key is a normal dictionary key but the value is a weak reference. 
When the object referenced in the value disappears then the key is also 
automatically deleted from the dictionary.

In a few cases (especially when testing C extensions) I have wanted to be 
sure that the data structures all disappeared neatly when expected. The 
setup for the tests creates an empty dictionary, each object is added to 
the dictionary using a tuple (id, somestring) as the key, and the tearDown 
method for the tests checks that the dicionary is empty (and if not it 
prints out the keys of the items that still exist).

Actual access to the weak dictionary is wrapped up in a class to make it 
more obvious what is happening.

Another good use for weak references is for objects which can be shared 
(e.g. the flyweight pattern). Typically the state of such objects is 
determined by the arguments passed to the constructor. In this case you use 
a factory function (or define __new__ in a newstyle class) which checks a 
weak dictionary keyed on the constructor arguments to see whether a 
suitable object already exists. If so you return the object, if not you 
create a new one and add it to the dictionary before returning it.

I believe that the latest versions of wxPython do something similar. They 
have to wrap a Python object around each wxWindows object and previously 
you could end up with several different Python wrappers for the same 
wxWindows object. The latest versions use a weak dictionary to ensure that 
the same object is reused as long as it still exists.
 
-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list