Repository navigation
Feat: add the to_dict() - #1288
Conversation
Merging this PR will degrade performance by 10.87%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ❌ | test_multidict_getall_str_hit[cs-c] |
33.8 ms | 38.1 ms | -11.3% |
| ❌ | test_cimultidict_getall_istr_hit[c] |
32.6 ms | 36.7 ms | -11.29% |
| ❌ | test_multidict_getall_str_hit[ci-c] |
35.1 ms | 39 ms | -10.03% |
Tip
Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.
Comparing rodrigobnogueira:feat/to-dict (bc63ab1) with master (cc8c06a)
0fe5e80 to
ed6d373
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1288 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 29 31 +2
Lines 4259 4449 +190
Branches 324 337 +13
==========================================
+ Hits 4259 4449 +190
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:
|
|
About the Coveralls Coverage Metrics |
"""Benchmark comparing C vs Python implementation of to_dict()."""
import timeit
import gc
from multidict._multidict import MultiDict as CMultiDict
from multidict._multidict_py import MultiDict as PyMultiDict
def create_multidict(cls, num_keys: int, vals_per_key: int):
items = [(f"key{i % num_keys}", f"value{i}") for i in range(num_keys * vals_per_key)]
return cls(items)
def benchmark_to_dict(md, iterations: int = 1000) -> float:
# Disable GC during timing to reduce noise
gc_old = gc.isenabled()
gc.disable()
try:
def run():
md.to_dict()
return timeit.timeit(run, number=iterations)
finally:
if gc_old:
gc.enable()
def run_benchmark(num_keys: int, vals_per_key: int, iterations: int = 1000) -> None:
total_items = num_keys * vals_per_key
c_md = create_multidict(CMultiDict, num_keys, vals_per_key)
py_md = create_multidict(PyMultiDict, num_keys, vals_per_key)
c_time = benchmark_to_dict(c_md, iterations)
py_time = benchmark_to_dict(py_md, iterations)
speedup = py_time / c_time if c_time > 0 else 0
print(f"| {num_keys:>6} | {vals_per_key:>6} | {total_items:>7} | {c_time*1000:>10.2f} | {py_time*1000:>10.2f} | {speedup:>7.2f}x |")
def main() -> None:
print("\n" + "=" * 80)
print("to_dict() Benchmark: C Extension vs Pure Python")
print("=" * 80)
print(f"\n{'Iterations per test:':30} 1000")
print(f"{'Time unit:':30} milliseconds (total for 1000 calls)\n")
print("| Keys | V/Key | Total | C (ms) | Py (ms) | Speedup |")
print("|--------|--------|---------|------------|------------|---------|")
scenarios = [
(10, 1),
(10, 10),
(100, 10),
(1000, 10),
(100, 100),
# Larger datasets to target >2s execution time for Python
(2000, 20), # 40,000 items
(5000, 10), # 50,000 items
]
for num_keys, vals_per_key in scenarios:
run_benchmark(num_keys, vals_per_key)
print("\n" + "=" * 80)
print("Speedup = Python time / C time (higher is better for C)")
print("=" * 80 + "\n")
if __name__ == "__main__":
main()to_dict() Benchmark: C Extension vs Pure PythonIterations per test: 1000
=====================================
|
There was a problem hiding this comment.
I would've applied some smarter logic like traverse all keys and gathering all the values up with something like getall(...) when going over keys since it would be a bit faster due to less time needing to check weather or not something is a list. Otherwise I think this is a good start in the right direction. There might be a quicker method though that you can try which I've attempted to visualize for you although I haven't benchmarked it but just incase here was my idea.
It's advantages mainly revolve around not needing to check on weather or not a key has already been used.
from multidict import MultiDict
# incase you need a visual of the logic I'm trying to explain
def to_dict(md: MutliDict[str]):
return {k: md.getall(k) for k in md.keys()}|
Hello @Vizonex , I've posted about using I haven't look into the Using the ================================================================================
|
| Keys | V/Key | Total | C (ms) | Py (ms) | Speedup |
|---|---|---|---|---|---|
| 10 | 1 | 10 | 0.93 | 18.91 | 20.27x |
| 10 | 10 | 100 | 5.66 | 495.79 | 87.56x |
| 100 | 10 | 1000 | 41.58 | 4644.99 | 111.72x |
| 1000 | 10 | 10000 | 424.65 | 53012.13 | 124.84x |
================================================================================
Speedup = Python time / C time (higher is better for C)
ee4cb7d to
d58c07f
Compare
Vizonex
left a comment
There was a problem hiding this comment.
Converter looks good. I have no complaints with this one. Great job with the pytest module also.
|
@rodrigobnogueira note that there's no need to use conventional commit prefixes as they only eat up space. Towncrier uses change note-based identifiers in file names. |
|
@rodrigobnogueira Do you think anything here could be pulled into aio-libs/aiohttp#7679? |
I'm guessing probably not, as it produces a list, rather than a concatenated string. I wonder how useful this feature will actually be (i.e. a user could just use a dict of lists in the first place if that's what they want...). |
I opened this PR a few months ago to address the 2022 issue requesting this feature. If this isn't the direction we want to take, I’m fine with closing it alongside #783 to avoid adding unnecessary complexity to the library. The value of this feature is probably a more performant |
I don't have a strong opinion, though it'd be nice to know if this is a somewhat common usecase for people. I'll let someone else decide if this is a good idea or not. |
@Dreamsorcerer I think it would be good for libraries such as msgspec to have this feature implemented. I could see some use-cases such as sterilizing header files for debugging an http request for instance or for other configuration systems. |
Use-case evidence, since that was the open question: this mirrors an established convenience on multidict-shaped types. Werkzeug's MultiDict has exactly this as to_dict(flat=False), and Django's QueryDict exposes it through .lists(). Meanwhile all review notes are addressed, to_dict() is now documented in the API reference, and the full suite is green on 3.12 and 3.13t. |
08e8338 to
f865f2c
Compare
Confidence Score: 5/5No blocking failure remains; the change is safe to merge. No accepted P0 or P1 findings remain. The public conversion behavior passed on both the C-extension and pure-Python implementations, and the earlier mutation path now rejects the reentrant change.
What T-Rex did
Reviews (5): Last reviewed commit: "Apply suggestions from code review" | Re-trigger Greptile |
to_dict() returns a plain dict mapping every key to the list of all its values, grouped by key identity, for MultiDict, CIMultiDict and both proxies. Unlike dict(md) it keeps every value, and unlike a getall() comprehension it emits one entry per case-insensitive key. Squashed onto master after the clang-format 23 restyle.
Replaces the second dict that mapped identity to value list. md_to_dict() walks the entries in insertion order and, for each key it has not collected yet, gathers that key's values the way md_get_all() does, leaving the visit marks in place so the key's later duplicates test as collected, and clearing every mark once at the end. The marks are held only over the value walk, which runs no Python. Building the keys and filling the result dict both can: a str subclass may run its own __hash__, __eq__ or __del__ from there, and a marked entry reads as a different hash, so code re-entering the multidict would find the collected keys missing and could strand entries the next resize indexes by a marked hash. Those two steps therefore run afterwards, over the positions the walk recorded, with nothing marked, and a mutation from there is refused the way it is during iteration.
getall() already returns a new list.
Adds the cases the new walk needs: lookups still work once to_dict() has marked and unmarked every entry, deleted entries are skipped, a key's __hash__ sees the whole multidict, and mutating from it is refused. Covers MultiMapping.to_dict() with a mapping that only the ABC serves. Drops the future import and the docstrings that restated the test names, and stops binding the unused to_dict() result in the leak script.
f865f2c to
1b96382
Compare
Building and hashing a key runs a str subclass's own code, and the C walk already refuses a mutation made from there. The pure-Python one accepted it and folded the result in, so the two backends disagreed on the same input. It now raises the same way iterating does. The C check moves to the end of each step, which is where it has to be anyway: a mutation can move the table, and the next step reads an entry by position.
Takes the multidict from the fixture rather than the C class, so the case runs against the pure-Python build too. Gives the key classes the __eq__ that goes with overriding __hash__, and drops the overloads from the test mapping, whose signatures are narrow enough to state directly.
006511a to
20f274b
Compare
|
Great job! |
What do these changes do?
Implement
to_dict()methods forMultiDict,CIMultiDict,MultiDictProxy, andCIMultiDictProxy. This method groups values with the same key into a list.Implementation Details
multidict_to_dictin_multidict.cwith directPyDictandPyListmanipulation for performance.to_dictin_multidict_py.py.tests/test_to_dict.py, including verification of order preservation, case-insensitivity, mixed types, and proxy mutation isolation.tests/isolated/multidict_to_dict.py) and integrated it into the CI suite (tests/test_leaks.py). Validated with intentional leak inserted in code (removed after test).Example
Are there changes in behavior for the user?
No existing behavior changes. This adds a new method
to_dict()Related issue number
Fixes #783 (Add
to_dictmethod)Checklist