ANN.: Beta 1.0 of Weak Reference Extension Module is now available

Gareth McCaughan Gareth.McCaughan at pobox.com
Fri Nov 17 01:11:28 CET 2000


Johann Hibschman wrote:
>>>> Looks neat!  But maybe you could answer me a quick question, since I
>>>> really don't understand weak references.
> 
>> Suppose you are designing a cache.
> 
> It's still not obvious to me.  Say I had a database that I was
> caching.  Then
> 
>   x = database.get('RECORD_ID')
> 
> would only get the file from disk once, etc.  But the cache itself is
> invisible; it's entirely under the hood.  Once you have the data
> object, you have it.
> 
> Are you saying that once you have the object, something weird might
> happen elsewhere that means you no longer have it?  That seems like a
> sign that you don't really have the object at all, or that you don't
> have synchronization working quite right.

You do a database.get. It returns a (perfectly ordinary)
reference to the object. It *also* updates an internal
"weak hash table" so that it contains the mapping from
RECORD_ID to the object. If you throw away your copy of
the object, then subsequent database retrievals will
get it quickly via the hash table until it happens to
get GCed. If the object *does* get GCed (at a time when
user-visible stuff isn't holding on to it) then the
next attempt at fetching it will see a NIL or Null or
None or whatever your preferred language calls its
null value, and so will go back to the database itself.

Another use for weak references: You build a class that
remembers what all its instances are, but you still want
the instances to disappear when there are no "ordinary"
references to them. In languages with support for finalization
(like Python and C++) you do this in the __del__ method,
or destructor, or whatever you want to call it; in languages
without such support (like Common Lisp) you do it by making
the class's references to its instances weak references.

-- 
Gareth McCaughan  Gareth.McCaughan at pobox.com
sig under construc



More information about the Python-list mailing list