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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

angela-tarantula
Copy link

@angela-tarantula angela-tarantula commented May 8, 2025

Closes #132762

Summary

dict_set_fromkeys() was only sizing its new table by the size of the iterable input, ignoring any existing entries in the dictionary. This triggered an infinite loop in dictresize() whenever the new dictionary size was too small to reinsert those entries. This patch adds the same Py_MAX(…, DK_LOG_SIZE(mp->ma_keys)) guard that dict_dict_fromkeys() uses, so we never accidentally shrink the table below its current capacity. The relevant test case baddict3 has been updated to cover this edge case.

For more background, see my proposal.

3 New Regression Tests

Ever since the fast path was updated, the slow path completely lost test coverage. To rectify this, I added 3 new tests:

  • 1 slow-path test when the iterable input is neither a set nor a dictionary
  • 1 slow-path test when fromkeys() is called on a proper subclass of dict, baddict4
  • 1 fast-path test when the input is a set (worth testing explicitly now that dict_dict_fromkeys() and dict_set_fromkeys() are separate)

Thanks for the review! @DinoV @colesbury

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
@python-cla-bot
Copy link

python-cla-bot bot commented May 8, 2025

All commit authors signed the Contributor License Agreement.

CLA signed

@bedevere-app
Copy link

bedevere-app bot commented May 8, 2025

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

dict_set_fromkeys() calculates size of dictionary improperly
1 participant