Repository navigation
Keep the implicit None default of setdefault() in the module state - #1553
Merged
Merged
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1553 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 41 41
Lines 7014 7022 +8
Branches 610 610
=========================================
+ Hits 7014 7022 +8
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
asvetlov
marked this pull request as ready for review
September 24, 2026 07:51
Contributor
|
setdefault() called without a default built the constant on every call and carried a flag to release it again, although only the inserting call consumes it. Hold one strong reference in the module state and borrow it per call; md_set_default() references whatever it stores, so the borrow is enough. Producing the constant on the insert path instead would put Py_GetConstant() inside md_set_default()'s critical section. That is fine on 3.13+, but the pythoncapi_compat shim used on 3.10 to 3.12 initialises its table lazily and calls PyLong_FromLong(), so a first call landing there could collect under the lock. md_set_default() is also public as MultiDict_SetDefault(), so its NULL contract is not ours alone to change. Callgrind, 200k calls: setdefault(key) on a present key drops 0.85%, setdefault(key, default) 0.12%, and the inserting call is unchanged.
Follow-up to the previous commit: rather than have multidict_setdefault() pick the constant up from the module state, let md_set_default() do it, so every caller including the public C API gets the same treatment. The substitution happens before the critical section is taken, which is why the module state holds the constant instead of Py_GetConstant() being called there; the pythoncapi_compat shim used on 3.10 to 3.12 initialises its table lazily and calls PyLong_FromLong(), so a first call landing under the lock could collect. MultiDict_SetDefault() inherits this through capsule.h, so document NULL in docs/capi.rst and cover it from _testcapi.c and test_capi.py. The Cython wrapper cannot express a NULL object, but passing None is read the same way, so default_value simply gains a None default, which also makes the signature match the Python method. MultiDict_CAPI_VERSION is left at 1 on purpose. It guards a client built against a newer header from an older runtime, and version 1 has not been released yet: the capsule landed after v6.9.1, so no runtime exists that would reject NULL.
asvetlov
force-pushed
the
setdefault-none-in-state
branch
from
September 24, 2026 08:10
13e55de to
773ff37
Compare
5 of 6 tasks
asvetlov
added a commit
that referenced
this pull request
Sep 24, 2026
<!-- Thank you for your contribution! --> ## What do these changes do? The published numbers had gone stale for the operations the object-shell pools made cheaper. AGENTS.md asks for the tables to be refreshed in the same PR as the change that moves them; #1542 landed without it, so this catches them up. Collected again on the environment the tables record. Rows that moved by more than 2%, GIL build: | row | `MultiDict` | `CIMultiDict` | | --- | ---: | ---: | | `cls()` | -24.7% | -20.7% | | `d.copy()`, 20 items | -9.4% | -7.7% | | `cls(items)`, 20 items | -4.5% | -3.1% | | `d.setdefault(key, v)`, new key | -3.7% | -2.2% | | `d[key] = v`, existing key | -3.1% | - | | `d[key] = v`, new key | -2.7% | - | The first three are the multidict and proxy shell pools from #1542; the `setdefault()` and `d[key] = v` rows are #1553 keeping the implicit default in the module state. No `dict` row moved, which is the control. ## Are there changes in behavior for the user? No. Documentation only; the measurements themselves are unchanged code. ## Is it a substantial burden for the maintainers to support this? No. ## Related issue number Follows up #1542. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist — N/A, documentation only - [x] Documentation reflects the changes - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` — N/A, already listed - [x] Add a new news fragment into the `CHANGES/` folder - [x] `make doc-spelling` passes and any new technical words are added to `docs/spelling_wordlist.txt` <details> <summary>Agent run details (optional, for reviewers)</summary> Collected with `benchmarks/callgrind_driver.py` on CPython 3.14.7 and 3.14.7t, `PYTHONHASHSEED=0`, client-request bracketing, one virtualenv per build. The GIL virtualenv needs `pytest-codspeed` installed, or the driver counts the whole process and `render_tables.py` refuses the result rather than publishing numbers that undercount every destructive operation. </details> Drafted with Claude Opus 5; reviewed by @asvetlov.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What do these changes do?
setdefault()called without an explicit default built the implicitNoneon every call, then carried a flag to release it again, althoughonly the call that actually inserts consumes it.
md_set_default()nowreads a
NULLvalue asNone, so the method simply forwards what itparsed and the flag, its branch and the
Py_CLEAR()all go away.The constant lives in the module state rather than coming from
Py_GetConstant()at the point of use, because the substitution happensjust before the critical section is taken. On 3.13+ either would do; on
3.10 to 3.12 the
pythoncapi_compatshim initialises its table lazilyand calls
PyLong_FromLong(), so a first call landing under the lockcould collect.
Instruction counts against
cd92a6c, callgrind, 200k calls:d.setdefault(key), present keyd.setdefault(key, default), present keyd.setdefault(key), insertingThe inserting call is unchanged, as expected: it still stores the same
constant, just one that was not built for the occasion.
Only the C extension is touched; the pure-Python implementation is
unchanged.
Are there changes in behavior for the user?
Not at the Python level;
setdefault()returns and stores exactly whatit did before.
The public C API gains a little:
MultiDict_SetDefault()forwardsstraight to
md_set_default(), so it now acceptsNULLfordefault_value and reads it as
None, where the documentationpreviously called the argument required.
docs/capi.rstsays so, andboth
_testcapi.cand_testcyapi.pyxexercise it.MultiDict_CAPI_VERSIONstays at 1 deliberately. It exists to stop aclient built against a newer header from running on an older runtime,
and version 1 has not shipped: the capsule landed after v6.9.1, so there
is no released runtime that would reject a
NULLdefault. Bumping wouldannounce a boundary no client can be on the wrong side of.
The Cython wrapper cannot express a
NULLobject, but passingNoneisread identically, so
default_valuejust gained aNonedefault, whichincidentally makes its signature match the Python method.
Is it a substantial burden for the maintainers to support this?
No. It removes a local variable and a branch from the method, adds one
field to the module state next to the interned names already there, and
leaves
md_set_default()'s behaviour for a non-NULLdefault untouched.Related issue number
None. Follow-up to #1549, which did the same for
get().Checklist
CONTRIBUTORS.txt- N/A, no such file in this repoCHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtDrafted with Claude Code (Opus 5); reviewed by @asvetlov.
Agent run details (optional, for reviewers)
Both legs ran in their own venv, and the pure-Python leg in its own tree
copy, so neither picked up a stale
.so. The C leg ran withMULTIDICT_TEST_REQUIRE_CYAPI=1after building Cython, so the_testcyapihalf oftest_capi.pywas a hard requirement rather than askip.
Two tests cover the new
NULLpath through both harnesses, oneinserting and one finding an existing key. The Python-level paths were
already covered by
test_mutable_multidict.py, which assertssetdefault("key") == "one"andsetdefault("noexist") is None.Measurement notes: callgrind,
PYTHONHASHSEED=0, warm__pycache__,200k iterations, rebuilt from the same tree for each side. Cross-rebuild
noise on this harness measures at about 0.01%, which is what the
inserting row is showing.