[Python-ideas] Identity dicts and sets (original) (raw)

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Jan 3 16:03:02 CET 2013


On 3 January 2013 12:09, Serhiy Storchaka <storchaka at gmail.com> wrote:

On 03.01.13 05:37, Nick Coghlan wrote:

[SNIP] However, one important problem with this kind of data structure is that it is very easy to get into lifecycle problems if you don't store at least a weak reference to a real key (since id's may be recycled after an object is destroyed, as shown here: Of course, identity dict and set should got an ownership on its keys and values, as all other non-weak collections. Except lookup function they don't differ from their ordinary counterparts.

I think what Nick means is that if you implement this naively then you don't hold references to the keys:

class IdentityDict(dict): def setitem(self, key, val): dict.setitem(self, id(key), val) # No reference to key held when this function ends ...

A way to fix this is to store both objects in the value (with corresponding changes to getitem etc.):

class IdentityDict(dict): def setitem(self, key, val): dict.setitem(self, id(key), (key, val))

Oscar



More information about the Python-ideas mailing list