Skip to content

Make MultiDict.setdefault return the current value of duplicate keys - #504

Open
galafis wants to merge 1 commit into
Pylons:mainfrom
galafis:fix-multidict-setdefault-return
Open

galafis wants to merge 1 commit into
Pylons:mainfrom
galafis:fix-multidict-setdefault-return

Conversation

@galafis

@galafis galafis commented Oct 24, 2026

Copy link
Copy Markdown

MultiDict.getitem returns the last value for a repeated key, but setdefault() returns its first value. A caller checking or using the value returned by setdefault therefore receives a different value from the mapping's current value.

Search existing entries in reverse order, consistently with getitem. Extend the shared setdefault regression to check the return value, preserve all repeated values, and retain the missing-key default behavior. This covers both MultiDict and the query-string-backed GetDict.

Validation on Python 3.12.14: the two mutable-mapping regressions fail before the fix and two controls pass. After the fix, the full suite has 2395 passed, 3 skipped, 1 xfailed and 14 warnings. Black and git diff --check pass.

@agammann agammann left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I traced the duplicate-key case through __getitem__: with the existing fixture values for a ending in f, lookup returns f while the old forward setdefault loop returned the first value. Reversing the scan makes those APIs agree without dropping the other entries; the shared regression checks that getall remains unchanged and that a missing key still receives its default. I reviewed the diff and related methods; I did not run tests locally.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants