Skip to content

gh-132762: Fix underallocation bug in dict.fromkeys() and expand test coverage #133627

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

Merged
merged 5 commits into from
May 8, 2025
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
4 new tests for fromkeys() to ensure full coverage
previously covered:
 - fast path for dictionary inputs
 - fast path when object's constructor returns non-empty dict (too small
   for good coverage)

now additionally covered:
 - fast path for set inputs
 - slow path for non-set, non-dictionary inputs
 - fast path when object's constructor returns *large* non-empty dict
 - slow path when object is a proper subclass of dict
  • Loading branch information
angela-tarantula committed May 8, 2025
commit f32cc2833d9e5dec995637f97c3886ab23d42bae
21 changes: 19 additions & 2 deletions Lib/test/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,9 +338,17 @@ def __setitem__(self, key, value):
self.assertRaises(Exc, baddict2.fromkeys, [1])

# test fast path for dictionary inputs
res = dict(zip(range(6), [0]*6))
d = dict(zip(range(6), range(6)))
self.assertEqual(dict.fromkeys(d, 0), dict(zip(range(6), [0]*6)))

self.assertEqual(dict.fromkeys(d, 0), res)
# test fast path for set inputs
d = set(range(6))
self.assertEqual(dict.fromkeys(d, 0), res)
# test slow path for other iterable inputs
d = list(range(6))
self.assertEqual(dict.fromkeys(d, 0), res)

# test fast path when object's constructor returns large non-empty dict
class baddict3(dict):
def __new__(cls):
return d
Expand All @@ -349,6 +357,15 @@ def __new__(cls):
res.update(a=None, b=None, c=None)
self.assertEqual(baddict3.fromkeys({"a", "b", "c"}), res)

# test slow path when object is a proper subclass of dict
class baddict4(dict):
def __init__(self):
dict.__init__(self, d)
d = {i : i for i in range(1000)}
res = d.copy()
res.update(a=None, b=None, c=None)
self.assertEqual(baddict4.fromkeys({"a", "b", "c"}), res)

def test_copy(self):
d = {1: 1, 2: 2, 3: 3}
self.assertIsNot(d.copy(), d)
Expand Down
Loading