Skip to content

Stop the pure-Python MultiDict mishandling falsy and arg= keyword arguments - #1842

Merged
asvetlov merged 3 commits into
aio-libs:masterfrom
provos:pure-python-falsy-arg
Dec 2, 2026
Merged

asvetlov merged 3 commits into
aio-libs:masterfrom
provos:pure-python-falsy-arg

Conversation

@provos

@provos provos commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

What do these changes do?

The pure-Python implementation (used on PyPy and with MULTIDICT_NO_EXTENSIONS=1) decides whether the positional argument was passed by testing its truth value. So the MultiDict / CIMultiDict constructors, extend(), update() and merge() treat a false non-iterable (None, 0, False, 0.0, 0j, or an object without __iter__ whose __len__() returns 0) as if no argument had been given. The C extension, like dict, raises TypeError: '<type>' object is not iterable for all of these. Empty iterables and mappings such as [], () and {} are accepted by both implementations and are not affected. The same truth test makes the pure-Python version reject an iterable of pairs whose __bool__() raises (a NumPy array of pairs, for example), which the C extension accepts.

$ python -c 'import multidict; multidict.MultiDict(0)'
TypeError: 'int' object is not iterable
$ MULTIDICT_NO_EXTENSIONS=1 python -c 'import multidict; print(multidict.MultiDict(0))'
<MultiDict()>

This is a regression in 6.2.0. In 6.1.0 the pure-Python version raised TypeError like the C extension. #1046 changed the default to None and the check in _parse_args() to if arg:.

This PR uses the module's existing sentinel as the default, as getall() / getone() / popone() already do, and tests arg is not sentinel. It also drops | None from MDArg, which only typed the old default. The C extension has never accepted None there. If you would rather keep None accepted, a one-line if arg is not None: fixes every other case and the __bool__() case, and I can switch to that.

A second commit fixes a related bug in the pure-Python implementation. _locked_pair_always, the lock-pairing wrapper around these four methods, did not make its first parameter positional-only. So MultiDict(arg=1), extend(arg=1), update(arg=1) and merge(arg=1) bound arg instead of adding a key named arg, and raised TypeError. The C extension adds the key, as did the pure-Python implementation up to 6.8.0. This regressed in 6.9.0 with #1449. The wrapper now has a / after arg.

The new tests run over both implementations through the existing any_multidict_class fixture. They cover the falsy non-iterables for each entry point, with and without keyword arguments, an iterable whose __bool__() raises, and arg passed as a keyword.

Are there changes in behavior for the user?

Yes. With the pure-Python implementation, passing None, 0, False or another falsy non-iterable to these methods now raises TypeError, as it already does with the C extension. An iterable whose __bool__() raises is now accepted, and an arg keyword argument becomes a key, as with the C extension. Nothing changes for C extension users.

Is it a substantial burden for the maintainers to support this?

No. It is a small change to the existing argument parsing and brings the two implementations back in line.

Related issue number

None.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes (N/A: the documented signatures do not change)
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt (N/A: no CONTRIBUTORS.txt 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 (not run locally: libenchant is not installed)
Test runs

On master at 6f1f778 with this branch, CPython 3.13, macOS arm64:

  • C extension build: pytest tests -q --no-cov: 4422 passed, 184 skipped
  • Pure Python (separate tree without built extensions): MULTIDICT_NO_EXTENSIONS=1 pytest tests -q --no-cov --no-c-extensions: 1771 passed, 24 skipped
  • The 56 new falsy-argument tests fail on the pure-Python implementation without the first commit, and the 8 new keyword tests fail without the second
  • ruff check, ruff format --check and mypy (repo config) pass

Drafted with Claude Code (Claude Opus 5.5); reviewed by @provos.

The pure-Python implementation defaulted the positional argument of the
constructors, extend(), update() and merge() to None and tested it by
truth value, so None, 0, False and other false non-iterables were
silently treated as if no argument had been passed. The C extension, like
dict, raises TypeError for them. The truth test also rejected iterables
whose __bool__() raises. This regressed in 6.2.0 with aio-libs#1046.

Use the existing sentinel as the default and test identity against it,
and drop None from MDArg, which only existed to type the old default.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Nov 24, 2026
Comment thread tests/test_update.py Dismissed
@codspeed

codspeed Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 730 untouched benchmarks


Comparing provos:pure-python-falsy-arg (45a0c1d) with master (009148b)

Open in CodSpeed

The lock-pairing wrapper around the pure-Python constructors, extend(),
update() and merge() did not make its first parameter positional-only,
so MultiDict(arg=1) bound arg instead of adding a key named arg, and
raised TypeError. The C extension adds the key. This regressed in 6.9.0
with aio-libs#1449.
@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.68%. Comparing base (6f1f778) to head (45a0c1d).
⚠️ Report is 5 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1842      +/-   ##
==========================================
+ Coverage   98.67%   98.68%   +0.01%     
==========================================
  Files          51       51              
  Lines       10257    10352      +95     
  Branches      868      870       +2     
==========================================
+ Hits        10121    10216      +95     
  Misses        132      132              
  Partials        4        4              
Flag Coverage Δ
CI-GHA 98.68% <100.00%> (+0.01%) ⬆️
pytest 98.68% <100.00%> (+0.01%) ⬆️

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.

@provos provos changed the title Stop the pure-Python MultiDict taking a false argument for no argument Stop the pure-Python MultiDict mishandling falsy and arg= keyword arguments Nov 24, 2026
@provos

provos commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

The CodeQL "Module-level cyclic import" error on multidict/_multidict_py.py:31 is about an existing import, not a new cycle. _abc.py imports istr from _multidict_py only under if TYPE_CHECKING:, so the cycle does not exist at runtime, and from ._abc import MDArg is unchanged on master. My guess is that CodeQL reports it as new because this PR edits the MDArg definition line, but I can't see the repository's existing alerts to confirm.

The notice on tests/test_update.py (a __bool__ that raises ValueError) is intentional: the helper mimics a NumPy array, whose __bool__ raises ValueError for more than one element.

@provos
provos marked this pull request as ready for review November 24, 2026 00:43
@greptile-apps

greptile-apps Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 Tier: apexRetriggerView in Greptile

[Low impact] The PR appears safe to merge; no new actionable issues were found.

Reviews (2) · Last reviewed commit: "Update tests/test_update.py" · Reviewed by Greptile

Comment thread tests/test_update.py Resolved
Comment thread tests/test_update.py Resolved
@greptile-apps

greptile-apps Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

security Security Review

This PR appears safe to merge from a security standpoint.

What was checked
  • The PR only changes how the pure-Python backend tells a missing argument apart from a falsy one; it touches no auth, network, or C code.
  • Both backends now agree: I verified the C extension's _multidict_extend_parse_args and _md_seq_prepare already raised TypeError for falsy non-iterables and treated arg= as a key, and the new sentinel check reproduces that.
  • The lock-pairing wrapper still takes the right locks: _other_lock(sentinel) returns no lock, and eq, the only other method using the wrapper, always gets its argument positionally.
  • A failed update, extend, or merge with a non-iterable leaves the dict's contents unchanged, since entries are only added after the argument is confirmed iterable.
  • No secrets, dependencies, CI configuration, or size limits changed in this diff.

@asvetlov
asvetlov merged commit 526c0e7 into aio-libs:master Dec 2, 2026
57 checks passed
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.

3 participants