Repository navigation
Reject arguments passed both positionally and by name - #1545
Conversation
parse2() special-cased each shape of the keyword tuple, and the cases
where a name repeated an argument already bound positionally were not
among them. The surplus arguments were dropped instead of rejected, so
md.get("a", "b", key="c") returned a value for "a", and add() was worse:
md.add("a", key="k", value="v") read the value out of the first keyword
slot and stored ("a", "k").
Replace the special cases with a walk over the keyword tuple that binds
each name and rejects one that is already bound, mirroring how CPython
binds arguments for an equivalent def, including reporting the leftmost
offending keyword. This also fixes the arity messages: the labels for
the two minargs values were swapped, so methods with an optional second
argument claimed to take exactly one, and add() claimed to take a range.
The two names are distinct, so the walk compares the one still unbound
first; that keeps the common get(key, default=...) form at the single
string comparison it used to cost.
The pure-Python implementation already behaved this way and is unchanged.
Merging this PR will improve performance by 14.24%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ⚡ | test_create_multidict_with_dict[ci-c] |
100.3 µs | 87.8 µs | +14.24% |
Tip
Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.
Comparing asvetlov:parse2-argument-binding (84d627a) with master (372d632)
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1545 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 40 40
Lines 6820 6842 +22
Branches 596 596
=========================================
+ Hits 6820 6842 +22
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:
|
|
<!-- Thank you for your contribution! -->
## What do these changes do?
Three changes to the argument handling of the C extension, no behaviour
change in any of them.
`parse2()` compiled to a single outlined clone shared by all eleven call
sites and was inlined nowhere, so `md.get(key)` paid a call into the
keyword machinery it never used. The all-positional case now binds in
the inline wrapper, five instructions at the call site, and the rest
moved to a `COLD parse2_slow()`. Since the keyword walk is out of line
anyway, it takes the tuple through `PyTuple_GET_SIZE()` and
`PyTuple_GET_ITEM()`; all eleven methods are
`METH_FASTCALL | METH_KEYWORDS`, so `kwnames` is a tuple or `NULL` and
the error branches of the checked calls were unreachable.
Parameter names are now interned in the module state and matched against
`kwnames` by identity before falling back to a comparison, which is what
`find_keyword()` in CPython's `Python/getargs.c` does. A call written as
`get(key=k)` settles on a pointer compare; the `memcmp()` it replaces
was
45% of the keyword path. The fallback is not optional: `get(**{"key":
k})`
builds names that never reach the intern table, and there is a test for
exactly that.
Finally, `multidict_get()` built the implicit `None` default on every
call and carried a flag to release it again, although it is only
reachable when the key is absent. It now does the lookup directly and
produces the constant on the miss path, where it is the return value.
`setdefault()` keeps the old shape, since it has to hand the default to
`md_set_default()` inside the critical section.
Instruction counts against `9682ba1`, callgrind, 200k calls:
| case | master | this branch | |
| --- | --- | --- | --- |
| `md.get(key)` | 506,599,099 | 492,590,531 | -2.77% |
| `md.get(key, default=None)` | 560,167,840 | 538,574,218 | -3.85% |
| `md.getone(key=key)` | 553,395,042 | 531,801,895 | -3.90% |
| `md.get(key, None)` | 508,367,864 | 498,974,074 | -1.85% |
| `md.getone(key)` | 501,769,613 | 493,572,776 | -1.63% |
| `md.getall(key)` | 576,882,245 | 569,485,981 | -1.28% |
| `md.add(key, value)` | 752,475,828 | 743,272,580 | -1.22% |
Only the C extension is touched; the pure-Python implementation is
unchanged.
## Are there changes in behavior for the user?
No. The same calls succeed, the same ones raise, and the messages are
identical. A behaviour matrix of 27 argument combinations compared
against the pure-Python backend is unchanged by this branch.
## Is it a substantial burden for the maintainers to support this?
No, though two of the assumptions are worth knowing about. The tuple
macros rely on every `parse2()` caller staying
`METH_FASTCALL | METH_KEYWORDS`, and the identity match relies on the
module state holding interned names, so `PyUnicode_InternFromString()`
there is load bearing rather than incidental.
## Related issue number
None. Follow-up to #1545.
## Checklist
- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes - N/A, no documented behaviour
changes
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` - N/A, no such file in this repo
- [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`
Drafted with Claude Code (Opus 5); reviewed by @asvetlov.
<details>
<summary>Agent run details (optional, for reviewers)</summary>
Both legs ran in their own venv, and the pure-Python leg in its own tree
copy, so neither picked up a stale `.so`.
```
C extension: pytest tests -q 2444 passed, 120 skipped
pure Python: MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions
1188 passed, 11 skipped, 1191 deselected
lint: pre-commit run --all-files all hooks passed
docs: make doc-spelling build succeeded
```
Measurement notes: callgrind, `PYTHONHASHSEED=0`, warm `__pycache__`,
200k iterations. Cross-rebuild noise was measured at about 0.01% by
building identical source twice and comparing, so the deltas above are
well clear of it.
One rejected variant, recorded so it is not retried: screening the name
comparison with an inline first-character check before
`PyUnicode_CompareWithASCIIString()` regressed the keyword paths by 0.5
to 0.8%. The common keyword forms hit on the first name tried, so there
is no `memcmp()` to skip and the screen is pure overhead. Identity
matching was the change that actually paid.
</details>
What do these changes do?
parse2()in_multilib/parser.henumerated the shapes the keywordtuple could take, and the shapes where a keyword repeats an argument
already bound positionally were not among them. The surplus arguments
were dropped rather than rejected, so
md.get("a", "b", key="c")quietly returned the value for
"a", andadd()was worse:md.add("a", key="k", value="v")read its value out of the firstkeyword slot and stored
("a", "k").The enumeration is replaced by a walk over the keyword tuple that binds
each name and rejects one that is already bound, mirroring how CPython
binds arguments for an equivalent
def, down to reporting the leftmostoffending keyword. That also corrects the arity messages, whose two
minargslabels were swapped: methods with an optional second argumentclaimed to take exactly one, and
add()claimed to take a range.The two parameter names are distinct, so the walk compares the one still
unbound first. Without that,
get(key, default=...)pays a secondPyUnicode_CompareWithASCIIString(), which measured as +4.3% on thatcall; ordering it this way brings it back to +0.87%.
Only the C extension is affected. The pure-Python implementation already
raised
TypeErrorfor every one of these and is unchanged; it served asthe oracle for the expected messages.
Are there changes in behavior for the user?
Yes. Calls that were silently accepted now raise
TypeError, matchingthe pure-Python backend, and
md.add("a", key="k", value="v")no longerstores a wrong value. The wording of some existing
TypeErrormessageschanged as a result.
Is it a substantial burden for the maintainers to support this?
No.
parse2()is shorter than it was, and the error precedence followsone rule instead of a case per keyword-tuple shape.
Related issue number
None.
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 were run in their own venv, and the pure-Python leg in its own
tree copy, so neither picked up a stale
.so.Reverting
parser.halone and rebuilding fails 38 of the new cases, allon the
-clegs; the-pylegs pass unchanged, which is what confirmsthe pure-Python backend was already correct.
Behaviour was compared against the pure-Python backend across 27
argument combinations. Before: 16 differed. After: 3 differ, all of them
pre-existing conventions rather than this bug. The C messages do not
count
self(but 3 were givenagainstbut 4 were given), andpure-Python
pop()delegates topopone(), so that name appears in itsmessage. The tests are written to hold on both backends, which is why
the arity assertions match a shape rather than an exact string.
Instruction counts, callgrind,
PYTHONHASHSEED=0, 200k iterations,against the same build before and after:
Run-to-run noise on this harness is about 0.01%.