Skip to content

Keep the implicit None default of setdefault() in the module state - #1553

Merged
asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:setdefault-none-in-state
Sep 24, 2026
Merged

asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:setdefault-none-in-state

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

setdefault() called without an explicit default built the implicit
None on every call, then carried a flag to release it again, although
only the call that actually inserts consumes it. md_set_default() now
reads a NULL value as None, so the method simply forwards what it
parsed 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 happens
just before the critical section is taken. On 3.13+ either would do; on
3.10 to 3.12 the pythoncapi_compat shim initialises its table lazily
and calls PyLong_FromLong(), so a first call landing under the lock
could collect.

Instruction counts against cd92a6c, callgrind, 200k calls:

case master this branch
d.setdefault(key), present key 491,825,979 486,878,820 -1.01%
d.setdefault(key, default), present key 494,626,107 493,681,201 -0.19%
d.setdefault(key), inserting 290,700,236 290,812,020 +0.04%

The 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 what
it did before.

The public C API gains a little: MultiDict_SetDefault() forwards
straight to md_set_default(), so it now accepts NULL for
default_value and reads it as None, where the documentation
previously called the argument required. docs/capi.rst says so, and
both _testcapi.c and _testcyapi.pyx exercise it.

MultiDict_CAPI_VERSION stays at 1 deliberately. It exists to stop a
client 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 NULL default. Bumping would
announce a boundary no client can be on the wrong side of.

The Cython wrapper cannot express a NULL object, but passing None is
read identically, so default_value just gained a None default, which
incidentally 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-NULL default untouched.

Related issue number

None. Follow-up to #1549, which did the same for get().

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt - N/A, no such file in this repo
  • Add a new news fragment into the CHANGES/ folder
  • make doc-spelling passes and any new technical words are added to docs/spelling_wordlist.txt

Drafted 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 with
MULTIDICT_TEST_REQUIRE_CYAPI=1 after building Cython, so the
_testcyapi half of test_capi.py was a hard requirement rather than a
skip.

C extension:   MULTIDICT_TEST_REQUIRE_CYAPI=1 pytest tests -q
                                                  2691 passed, 33 skipped
pure Python:   MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions
                                                  1264 passed, 11 skipped, 1268 deselected
lint:          pre-commit run --all-files         all hooks passed
docs:          make doc-spelling                  build succeeded

Two tests cover the new NULL path through both harnesses, one
inserting and one finding an existing key. The Python-level paths were
already covered by test_mutable_multidict.py, which asserts
setdefault("key") == "one" and setdefault("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.

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 24, 2026
@codspeed

codspeed Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:setdefault-none-in-state (773ff37) with master (cd92a6c)

Open in CodSpeed

@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (cd92a6c) to head (773ff37).

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     
Flag Coverage Δ
CI-GHA 100.00% <100.00%> (ø)
pytest 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@asvetlov
asvetlov marked this pull request as ready for review September 24, 2026 07:51
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 24, 2026 07:51
@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

The outstanding repository requirement for past-tense news wording must be satisfied before merging.

Reviews (2) · Last reviewed commit: "Read a NULL default as None in md_set_de..."

Comment thread CHANGES/1553.misc.rst Resolved
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
asvetlov force-pushed the setdefault-none-in-state branch from 13e55de to 773ff37 Compare September 24, 2026 08:10
@asvetlov
asvetlov merged commit 6657ea8 into aio-libs:master Sep 24, 2026
62 checks passed
@asvetlov
asvetlov deleted the setdefault-none-in-state branch September 24, 2026 08:31
@asvetlov asvetlov mentioned this pull request Sep 24, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant