Skip to content

Replace key if not identical to old key in dict #31685

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Lib/test/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,21 @@ def __hash__(self):
with self.assertRaises(Exc):
d1 == d2

def test_eq_replace(self):
class AlwaysEqualCmp(object):
def __eq__(self, other):
return True

def __hash__(self):
return 1

o1 = AlwaysEqualCmp()
d3 = {}
d3[o1] = 1
o2 = AlwaysEqualCmp()
d3[o2] = 2
assert tuple(d3.keys())[0] is o2

def test_keys_contained(self):
self.helper_keys_contained(lambda x: x.keys())
self.helper_keys_contained(lambda x: x.items())
Expand Down
13 changes: 13 additions & 0 deletions Lib/test/test_weakref.py
Original file line number Diff line number Diff line change
Expand Up @@ -1797,6 +1797,19 @@ def test_weak_keyed_bad_delitem(self):
self.assertRaises(TypeError, d.__getitem__, 13)
self.assertRaises(TypeError, d.__setitem__, 13, 13)

def test_weak_keyed_equal_replacement(self):
d = weakref.WeakKeyDictionary()
o1 = Object('1')
o2 = Object('1')
d[o1] = 1
d[o2] = 2
assert len(d) == 1
assert d[o2] == 2
assert tuple(d.keys())[0] is o2
del o1
assert len(d) == 1
assert tuple(d.keys())[0] is o2

def test_weak_keyed_cascading_deletes(self):
# SF bug 742860. For some reason, before 2.3 __delitem__ iterated
# over the keys via self.data.iterkeys(). If things vanished from
Expand Down
10 changes: 10 additions & 0 deletions Objects/dictobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1222,6 +1222,7 @@ Consumes key and value references.
static int
insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
{
PyObject *old_key;
PyObject *old_value;

if (DK_IS_UNICODE(mp->ma_keys) && !PyUnicode_CheckExact(key)) {
Expand Down Expand Up @@ -1279,6 +1280,15 @@ insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value)
return 0;
}

if (!DK_IS_UNICODE(mp->ma_keys)) {
PyDictKeyEntry *ep = &DK_ENTRIES(mp->ma_keys)[ix];
old_key = ep->me_key;
if (old_key != key) {
ep->me_key = key;
key = old_key;
}
}

if (old_value != value) {
if (_PyDict_HasSplitTable(mp)) {
mp->ma_values->values[ix] = value;
Expand Down