[Python-Dev] Equal but different keys in dicts

Tim Peters tim.peters at gmail.com
Sun Jul 11 07:09:59 CEST 2004


[Michael Chermside]
> ...
> My question is this: is this behavior intentional, or is it an "implementation
> detail"? If intentional, is there a reason for the choice, or is it just that
> one or the other behavior needed to be chosen?
>
> [PS: I'm hoping that a good answer to this question will allow me to close bug
> 748126]

It's undefined, but the docs could stand to explicitly point out that
it's undefined.  748126 is intimately related to the thread starting
here, BTW:

    http://mail.python.org/pipermail/python-dev/2003-June/035970.html

I don't think it's an accident that implementations are likely to keep
"the old key".  A natural way to code setitem(self, key, value) is

    if key in self:
        replace the value associated with key
    else:
        raise KeyError

While there was no deliberate attempt to do so, ZODB's BTrees (and
Buckets) also act this way:

>>> from BTrees.OOBTree import OOBTree
>>> s1 = 'a' + 'b'
>>> s2 = 'a' + 'b'
>>> id(s1)
10043520
>>> id(s2)  # s1 and s2 are == but not the same object
10044416
>>> b = OOBTree()
>>> b[s1] = 1
>>> id(b.keys()[0])
10043520
>>> b[s2] = 2   # replaces the value associated with s2 (== s1)
>>> len(b)   # still only 1 pair in this tree
1
>>> id(b.keys()[0])   # the key object didn't change
10043520
>>> b[s1]  # and the associated value did change
2
>>>


More information about the Python-Dev mailing list