[Python-Dev] Mundane dict __setitem__...

David Abrahams dave@boost-consulting.com
Tue, 03 Jun 2003 13:42:59 -0400


Guido van Rossum <guido@python.org> writes:

>> > Why?  You haven't given us much of a clue about your use case.
>> 
>> I did eventually, in another posting...
>
> I have scoured the archives, but have not found your exposition of why
> you would want this.  I only found the source of your
> misunderstanding.
>
> So I repeat the question (out of honest curiosity only): why would you
> want this?

Sorry, it seems it was a reply to an off-list reply:

-----------

sismex01@hebmex.com writes:

>> Anyone want to tell me it's a bad idea?  It seems like the more useful
>> of the two possible behaviors to me.
>>
>
> I believed hashing was done by value and not necessarily by
> object identity?

Absolutely.  The point is that two keys which compare equal may not
neccessarily be strictly equivalent.

I am using a dict which stores the same such object as both the key
and the value of each entry.  It basically implements a set which uses
only a part of a value object's data for key comparison and hashing.
A fairly common scenario.

For any given set of key it is important to be able to find the value
that is currently in the set.  When I replace the value for that key,
I could write:

   d[x] = x

But with no guarantees, the old value object won't be reclaimed since
it is still referenced as the key.  To reclaim the reference, I need

   del d[x]
   d[x] = x

Seems silly to me.

---

BTW, this is not a big deal for me; I don't use Python for work where
speed is critical anyway.  A related issue is that I think there
probably ought to be a deldefault method which removes the key if it
exists in the dict and returns the k,v pair.

Regards,
-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com