what is the use of weakref?

Duncan Booth me at privacy.net
Fri Jan 30 10:14:14 CET 2004


"ali" <rmangaliag at slu.edu.ph> wrote in
news:1jipe1-fqq.ln1 at news.slu.edu.ph: 

> i've seen a lot of times in programs but until now i still dont know
> the use of the weakref module... any help will be appreciated...
> thanks... 
> 

Normally in Python an object is never destroyed until you can no longer 
reference it. Occasionally it can be convenient to hold onto an object, but 
not to mind too much if it gets destroyed.

For example, say you had a word processing application with a complex data 
structure for each paragraph style that was used in a document. When 
someone changes the style of an existing paragraph, if it now matches the 
style of another paragraph you want to share the same data structure rather 
than creating a new one. What you could do here would be to make each 
paragraph hold a strong reference to the required data structure, but also 
store a weak value dictionary which maps the description of the paragraph 
style onto the data structures.

With this kind of setup, the entries in the weak value dictionary always 
exactly match the paragraph styles which are in use; as soon as a style is 
no longer used it can be released, but you never need to duplicate the 
complex data structure as a simple dictionary lookup will give you a 
suitable one if it exists.

In short weak references help you to share or reuse data structures while 
still allowing them to be freed automatically when no longer used.



More information about the Python-list mailing list