### Install dev dependencies and run test suite Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md Installs development dependencies and builds the C extension in place, then runs the test suite with pytest against the installed build. ```bash make install-dev # installs deps and builds the C extension in place make test # pytest -q against whichever build is installed ``` -------------------------------- ### Fork remote setup and PR creation Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md Use these commands to add your fork as a remote and push a branch for a pull request. The first command is one-time setup; the second is per-PR. `gh pr create` against aio-libs/multidict from a fork branch picks up the right base and head automatically. ```bash # one-time: add your fork as a remote alongside `origin` git remote add https://github.com//multidict ``` ```bash # per-PR: push the branch to your fork, then open the PR git push -u gh pr create --draft --repo aio-libs/multidict ``` -------------------------------- ### Run tests with C extension backend Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md Installs the package with the C extension (default) and runs the test suite. This is the standard backend for testing. ```bash # C extension (default) pip install -e . pytest -q ``` -------------------------------- ### Install multidict with pip Source: https://github.com/aio-libs/multidict/blob/master/README.rst Standard installation command for the multidict library. Requires Python 3 only. ```bash $ pip install multidict ``` -------------------------------- ### Create virtualenvs for GIL and free-threading builds Source: https://github.com/aio-libs/multidict/blob/master/docs/benchmark.rst Create one virtualenv per interpreter build to avoid measuring the wrong checkout. Install the package and development requirements in each environment. ```bash $ ~/.pyenv/versions/3.14.7/bin/python -m venv .venv-gil $ ~/.pyenv/versions/3.14.7t/bin/python -m venv .venv-ft $ for venv in .venv-gil .venv-ft; do > $venv/bin/python -m pip install -e . -r requirements/dev.txt > done ``` -------------------------------- ### Build Cython test extension locally Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md Install Cython requirements and rebuild the package without build isolation to compile the optional Cython test extension. Required because an isolated build would not see an ambiently installed Cython. ```bash pip install -r requirements/cython.txt pip install -e . --no-build-isolation --force-reinstall --no-deps ``` -------------------------------- ### Run pyperf benchmark for a specific implementation Source: https://github.com/aio-libs/multidict/blob/master/docs/benchmark.rst Use the --impl option to run benchmarks for a specific class of a specific implementation. For example, --impl multidict_c runs the C implementation. ```bash $ python benchmarks/benchmark.py --impl multidict_c ``` -------------------------------- ### to_dict() example Source: https://github.com/aio-libs/multidict/blob/master/docs/multidict.rst Return a dict mapping each key to a list of all its values, preserving insertion order. ```python >>> d = MultiDict([('a', 1), ('b', 2), ('a', 3)]) >>> d.to_dict() {'a': [1, 3], 'b': [2]} ``` -------------------------------- ### Run Callgrind driver with GIL and free-threaded interpreters Source: https://github.com/aio-libs/multidict/blob/master/docs/benchmark.rst Run the Callgrind driver with the interpreter you want to measure. Valgrind must be installed. The driver runs four Valgrind child processes per cell and reduces the results with the formula shown in the next snippet. ```bash $ .venv-gil/bin/python benchmarks/callgrind_driver.py -o gil.json $ .venv-ft/bin/python benchmarks/callgrind_driver.py -o ft.json ``` -------------------------------- ### Run hypothesis property/fuzz tests Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md Installs the hypothesis dependencies from requirements/pytest-hypothesis.txt, reinstalls the package to build the C extension, and runs the hypothesis tests. Passing -m hypothesis overrides the default marker expression that excludes them. One run covers both backends because fixtures import _multidict and _multidict_py directly. ```bash pip install -r requirements/pytest-hypothesis.txt pip install -e . # the C half of the matrix needs a built extension pytest -q -m hypothesis ``` -------------------------------- ### Tag the release commit Source: https://github.com/aio-libs/multidict/blob/master/RELEASE.md Annotated tag triggers CI/CD publication. Push the tag to upstream to start the workflow; expect 60-90 minutes before anything is publishable. ```bash git fetch upstream git tag -a vX.Y.Z -m "Release X.Y.Z" git push upstream vX.Y.Z ``` -------------------------------- ### Install multidict without C extensions Source: https://github.com/aio-libs/multidict/blob/master/README.rst Sets MULTIDICT_NO_EXTENSIONS=1 to skip compilation and use the pure-Python fallback. Note that the pure-Python version is dramatically slower (about 40 times more instructions than the C extension). ```bash $ MULTIDICT_NO_EXTENSIONS=1 pip install multidict ``` -------------------------------- ### Watching a multidict: callback, watcher registration, and watch setup Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Shows how to watch a multidict for changes. The callback on_header_change receives watcher_data (the module state) and user_data (the response). It handles deallocation, identity NULL events (CLEARED, CLONED, LOST, or batch), and content-length changes. MultiDict_AddWatcher registers the callback, and MultiDict_Watch attaches a specific response to a specific headers multidict. ```c #include typedef struct { PyObject *headers; Py_ssize_t content_length; } response; static int on_header_change(void *watcher_data, void *user_data, const MultiDict_WatchInfo *info) { my_mod_state *state = (my_mod_state *)watcher_data; response *resp = (response *)user_data; if (info->event == MultiDict_EVENT_DEALLOCATED) { /* `info->self` is at refcount 0 here: identity only. */ resp->headers = NULL; return 0; } if (info->identity == NULL) { /* CLEARED, CLONED, LOST or a batch bracket: recompute. */ return recompute(state, resp); } /* `identity` is already lowercased for a CIMultiDict. */ if (PyUnicode_CompareWithASCIIString(info->identity, "content-length") == 0) { return recompute(state, resp); } return 0; } static int module_exec(PyObject *mod) { my_mod_state *state = PyModule_GetState(mod); state->capi = MultiDict_GetCAPI(); if (state->capi == NULL) { return -1; } state->watcher_id = MultiDict_AddWatcher(state->capi, on_header_change, state); return state->watcher_id < 0 ? -1 : 0; } static int response_init(my_mod_state *state, response *resp) { resp->headers = CIMultiDict_New(state->capi, 8); if (resp->headers == NULL) { return -1; } /* Every change to *these* headers arrives with *this* response. */ return MultiDict_Watch(state->capi, state->watcher_id, resp->headers, resp); } ``` -------------------------------- ### Run tests with pure Python backend using MULTIDICT_NO_EXTENSIONS Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md Forces the pure Python implementation by setting MULTIDICT_NO_EXTENSIONS during install and test run. The flag is read on every import, so it must be set for the test run to make 'import multidict' resolve to _multidict_py. The --no-c-extensions flag deselects C-extension tests; without it, tests may fail with ModuleNotFoundError or run against a stale .so. ```bash # Pure Python MULTIDICT_NO_EXTENSIONS=1 pip install -e . --force-reinstall --no-deps MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions ``` -------------------------------- ### Get include directory with multidict.get_include() Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Returns the directory containing multidict_capi.h, to pass as an -I include path when building a C extension against it. Added in version 7.0. ```pycon >>> import multidict >>> multidict.get_include() '/.../site-packages/multidict' ``` -------------------------------- ### MultiDict_Watch Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Starts reporting changes of a multidict object to a watcher's callback. Returns 0 on success or -1 with an exception set on failure. ```APIDOC ## MultiDict_Watch ### Description Start reporting self's changes to watcher_id's callback, which will be passed user_data on every event. Returns 0 on success, -1 with an exception set on failure. ### Signature int MultiDict_Watch(MultiDict_CAPI *capi, int watcher_id, PyObject *self, void *user_data) ### Parameters - **capi** (MultiDict_CAPI*) - Required - Pointer to the MultiDict C API structure. - **watcher_id** (int) - Required - Watcher ID previously registered with MultiDict_AddWatcher. - **self** (PyObject*) - Required - The multidict object to watch. Can be MultiDict, CIMultiDict, MultiDictProxy, or CIMultiDictProxy instance. - **user_data** (void*) - Required - User data passed to the callback. Lifetime must outlive the watch. ### Return Value - **int** - 0 on success, -1 with an exception set on failure. ### Exceptions - **ValueError** - When watcher_id is not registered. ### Thread Safety Safe for concurrent use on the same object. ``` -------------------------------- ### get(key) Source: https://github.com/aio-libs/multidict/blob/master/docs/multidict.rst Returns the first value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so this method never raises a KeyError. ```APIDOC ## get(key) ### Description Return the **first** value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a `KeyError`. ### Method get ### Parameters - **key** - The key to look up ``` -------------------------------- ### Bad present-tense CHANGES fragment (early draft of CHANGES/1585.bugfix.rst) Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md This is an example of what not to write. It uses present tense ('is now') instead of past tense, which violates the convention for towncrier fragments. ```rst A failing watcher callback is now reported with a message naming the event, and the unraisable hook's ``object`` is now ``None``. ``` -------------------------------- ### Re-point tag to a new commit Source: https://github.com/aio-libs/multidict/blob/master/RELEASE.md Use when a tag's run never published anything. Delete any existing release, remove the tag locally and remotely, then re-tag and push to start a fresh run. ```bash gh release delete vX.Y.Z --repo aio-libs/multidict # only if one exists git push upstream :refs/tags/vX.Y.Z git tag -d vX.Y.Z git tag -a vX.Y.Z -m "Release X.Y.Z" git push upstream vX.Y.Z ``` -------------------------------- ### CHANGES fragment example (CHANGES/1310.bugfix.rst style) Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md Use this reStructuredText format for a towncrier news fragment. The body must be past tense, lead with a verb like 'Fixed', and end with '-- by :user:`github-handle`'. Do not include the issue or PR number in the body. ```rst Fixed a segmentation fault that could be triggered when getting an item -- by :user:`Vizonex`. ``` -------------------------------- ### Collect builds and render tables Source: https://github.com/aio-libs/multidict/blob/master/docs/benchmark.rst Run the callgrind driver with both builds to produce JSON files, then render the tables. Add --write docs/benchmark.rst to replace the block between the two marker comments in the file. ```bash $ .venv-gil/bin/python benchmarks/callgrind_driver.py -o gil.json $ .venv-ft/bin/python benchmarks/callgrind_driver.py -o ft.json $ python benchmarks/render_tables.py gil.json ft.json ``` -------------------------------- ### Run pyperf benchmark Source: https://github.com/aio-libs/multidict/blob/master/docs/benchmark.rst Run the pyperf benchmark for both classes (MultiDict and CIMultiDict) of both implementations (pure-Python and C), plus dict for comparison. Requires requirements/dev.txt and a stable OS environment. ```bash $ python benchmarks/benchmark.py ``` -------------------------------- ### Build docs and changelog draft Source: https://github.com/aio-libs/multidict/blob/master/RELEASE.md Run this command during preflight to build the documentation, including the changelog draft, and check spelling. It is part of the release checklist. ```bash make doc doc-spelling ``` -------------------------------- ### Compare implementations with pyperf compare_to Source: https://github.com/aio-libs/multidict/blob/master/docs/benchmark.rst Generate JSON results for the C and pure-Python implementations, then compare them with pyperf's compare_to command. The --impl option combined with compare_to gives a good picture of how an implementation performs. ```bash $ python benchmarks/benchmark.py --impl multidict_c -o multidict_c.json $ python benchmarks/benchmark.py --impl multidict_py -o multidict_py.json $ python -m pyperf compare_to multidict_c.json multidict_py.json ``` -------------------------------- ### Build release notes with towncrier and bump version Source: https://github.com/aio-libs/multidict/blob/master/RELEASE.md Run to prepare the release commit. The first command is a preview only; the second writes CHANGES.rst and removes fragments. The sed command updates the version in multidict/__init__.py. After running, verify CHANGES.rst heading format and that CHANGES/ contains only README.rst and .TEMPLATE.rst. ```bash python -Im towncrier build --draft --version X.Y.Z # preview only python -Im towncrier build --version X.Y.Z --yes # writes CHANGES.rst, # removes the fragments sed -i 's/^__version__ = .*/__version__ = "X.Y.Z"/' multidict/__init__.py ``` -------------------------------- ### C API usage: create, add, and iterate multidict Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Shows how to retrieve the C API via MultiDict_GetCAPI(), create a multidict with MultiDict_New(), add items with MultiDict_Add(), and iterate without building a list using MultiDict_ForEach(). The callback print_pair returns 1 to continue iteration; MultiDict_ForEach returns -1 on error. ```c #include static int module_exec(PyObject *mod) { my_mod_state *state = PyModule_GetState(mod); state->capi = MultiDict_GetCAPI(); if (state->capi == NULL) { return -1; } return 0; } static PyObject * make_headers(my_mod_state *state) { PyObject *md = MultiDict_New(state->capi, 2); if (md == NULL) { return NULL; } if (MultiDict_Add(state->capi, md, key1, value1) < 0 || MultiDict_Add(state->capi, md, key2, value2) < 0) { Py_DECREF(md); return NULL; } return md; } static int print_pair(void *user_data, PyObject *identity, Py_hash_t hash, PyObject *key, PyObject *value) { PyObject_Print(key, stdout, 0); printf(": "); PyObject_Print(value, stdout, 0); printf("\n"); return 1; /* keep going */ } static int print_all(my_mod_state *state, PyObject *md) { /* Visit every item, without building a list. */ return MultiDict_ForEach(state->capi, md, NULL, print_pair, NULL) < 0 ? -1 : 0; } static int print_values_for(my_mod_state *state, PyObject *md, PyObject *key) { /* Visit only the entries for `key`, equivalent to getall(key) but without allocating a list. */ return MultiDict_ForEach(state->capi, md, key, print_pair, NULL) < 0 ? -1 : 0; } ``` -------------------------------- ### Tune pyperf system settings Source: https://github.com/aio-libs/multidict/blob/master/docs/benchmark.rst Run pyperf's system tuning commands to adjust CPU frequency governor, turbo, address space randomization, and perf event rate. The reset command restores settings afterwards. ```bash $ sudo python -m pyperf system tune $ python -m pyperf system show $ sudo python -m pyperf system reset # afterwards ``` -------------------------------- ### Run docs spell check before pushing Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md CI fails on unknown words via sphinxcontrib.spelling; run this before pushing to avoid burning a CI run. ```bash make doc-spelling ``` -------------------------------- ### Verify extension module path in virtualenv Source: https://github.com/aio-libs/multidict/blob/master/docs/benchmark.rst Confirm each environment picked up the expected extension module by printing its file path. This helps ensure the benchmark measures the correct checkout. ```bash $ .venv-gil/bin/python -c "import multidict._multidict as m; print(m.__file__)" ``` -------------------------------- ### Collapsed details block for agent run details Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md Recommended footer shape for surfacing agent output (tests, lint) to reviewers while keeping the summary readable. ```markdown
Agent run details (optional, for reviewers) Tests: Lint:
``` -------------------------------- ### MultiDict_New Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Creates a new empty MultiDict instance. Returns NULL with an exception set on failure. ```APIDOC ## MultiDict_New ### Description Creates a new empty MultiDict instance. Returns NULL with an exception set on failure. ### Signature PyObject *MultiDict_New(MultiDict_CAPI *capi, Py_ssize_t prealloc_size) ### Parameters - **capi** (MultiDict_CAPI*) - Required - Pointer to the C API structure. - **prealloc_size** (Py_ssize_t) - Required - Hint for the number of items the multidict is expected to hold; pass 0 when there is no such estimate. ### Return Value - **PyObject*** - A new empty MultiDict instance, or NULL with an exception set on failure. ### Thread Safety Atomic. ``` -------------------------------- ### MultiDictProxy_New Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Creates a new MultiDictProxy wrapping the given argument. Returns NULL with an exception set on failure. ```APIDOC ## MultiDictProxy_New ### Description Creates a new MultiDictProxy wrapping the given argument. Returns NULL with an exception set on failure. ### Signature PyObject *MultiDictProxy_New(MultiDict_CAPI *capi, PyObject *arg) ### Parameters - **capi** (MultiDict_CAPI*) - Required - Pointer to the C API structure. - **arg** (PyObject*) - Required - The object to wrap. Must be a MultiDict, CIMultiDict, MultiDictProxy, or CIMultiDictProxy instance; anything else raises TypeError. ### Return Value - **PyObject*** - A new MultiDictProxy instance, or NULL with an exception set on failure. ### Thread Safety Atomic. The only touch on arg itself is a new reference (an atomic refcount increment); arg's hash table is never read. ``` -------------------------------- ### Regenerate benchmark tables with callgrind_driver and render_tables Source: https://github.com/aio-libs/multidict/blob/master/RELEASE.md Run before a release to refresh benchmark tables in docs/benchmark.rst. Requires Valgrind and one virtualenv per interpreter build on the same CPython patch release. The first two commands generate JSON files for GIL and free-threaded builds; the third renders the tables and writes the docs. ```bash .venv-gil/bin/python benchmarks/callgrind_driver.py -o gil.json .venv-ft/bin/python benchmarks/callgrind_driver.py -o ft.json python benchmarks/render_tables.py gil.json ft.json --write docs/benchmark.rst ``` -------------------------------- ### CIMultiDictProxy_New Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Creates a new CIMultiDictProxy wrapping the given argument. Returns NULL with an exception set on failure. ```APIDOC ## CIMultiDictProxy_New ### Description Creates a new CIMultiDictProxy wrapping the given argument. Returns NULL with an exception set on failure. ### Signature PyObject *CIMultiDictProxy_New(MultiDict_CAPI *capi, PyObject *arg) ### Parameters - **capi** (MultiDict_CAPI*) - Required - Pointer to the C API structure. - **arg** (PyObject*) - Required - The object to wrap. Must be a CIMultiDict or CIMultiDictProxy instance; a plain MultiDict is rejected with TypeError. ### Return Value - **PyObject*** - A new CIMultiDictProxy instance, or NULL with an exception set on failure. ### Thread Safety Atomic, for the same reason as MultiDictProxy_New(). ``` -------------------------------- ### Run inlining check with Python 3.14 and 3.14t Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md Run the inlining check script before pushing any change to the C code. It builds the extension with release flags and verifies the RULES table. The --show FUNCTION option prints what a function calls out of line today. ```bash tools/check_inlining.py \ --python ~/.pyenv/versions/3.14.7/bin/python3 \ --python ~/.pyenv/versions/3.14.7t/bin/python3.14t ``` -------------------------------- ### copy() Source: https://github.com/aio-libs/multidict/blob/master/docs/multidict.rst Returns a shallow copy of the dictionary. ```APIDOC ## copy() ### Description Return a shallow copy of the dictionary. ### Method copy ``` -------------------------------- ### CIMultiDict_New Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Creates a new empty CIMultiDict instance. Returns NULL with an exception set on failure. ```APIDOC ## CIMultiDict_New ### Description Creates a new empty CIMultiDict instance. Returns NULL with an exception set on failure. ### Signature PyObject *CIMultiDict_New(MultiDict_CAPI *capi, Py_ssize_t prealloc_size) ### Parameters - **capi** (MultiDict_CAPI*) - Required - Pointer to the C API structure. - **prealloc_size** (Py_ssize_t) - Required - Hint for the number of items the multidict is expected to hold; pass 0 when there is no such estimate. ### Return Value - **PyObject*** - A new empty CIMultiDict instance, or NULL with an exception set on failure. ### Thread Safety Atomic. ``` -------------------------------- ### multidict.get_include() Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Returns the directory containing the multidict C API header file, to be used as an include path when building a C extension. ```APIDOC ## multidict.get_include() ### Description Return the directory containing `multidict_capi.h`, to pass as an `-I` include path when building a C extension against it. ### Method Function ### Endpoint `multidict.get_include()` ### Returns - **str** - The directory path containing the header. ### Example ```pycon >>> import multidict >>> multidict.get_include() '/.../site-packages/multidict' ``` ``` -------------------------------- ### CIMultiDict keys converted to istr Source: https://github.com/aio-libs/multidict/blob/master/docs/multidict.rst Demonstrates that keys are converted to istr instances; the first key is an istr and retains its original spelling. ```python >>> dct = CIMultiDict([('Content-Type', 'text/html')]) >>> key = next(iter(dct)) >>> isinstance(key, istr), key (True, 'Content-Type') ``` -------------------------------- ### MultiDictProxy_New() Source: https://github.com/aio-libs/multidict/blob/master/docs/index.rst Creates a new MultiDictProxy object that wraps an existing MultiDict. ```APIDOC ## MultiDictProxy_New() ### Description Creates a new MultiDictProxy object that wraps an existing MultiDict. ### Method C API function ### Signature `MultiDictProxyObject* MultiDictProxy_New(MultiDictObject *md)` ### Parameters - `md` (MultiDictObject*) - The underlying MultiDict to wrap. ### Returns - `MultiDictProxyObject*` - A new MultiDictProxy object, or NULL on failure. ``` -------------------------------- ### MultiDict_New() Source: https://github.com/aio-libs/multidict/blob/master/docs/index.rst Creates a new empty MultiDict object. ```APIDOC ## MultiDict_New() ### Description Creates a new empty MultiDict object. ### Method C API function ### Signature `MultiDictObject* MultiDict_New(void)` ### Returns - `MultiDictObject*` - A new MultiDict object, or NULL on failure. ``` -------------------------------- ### MultiDict_New Source: https://github.com/aio-libs/multidict/blob/master/docs/cyapi.rst Creates a new, empty MultiDict instance. ```APIDOC ## MultiDict_New ### Description Creates a new, empty MultiDict instance. ### Signature `MultiDict_New(capi, prealloc_size) -> object` ### Parameters - **capi** - Required - The C API context. - **prealloc_size** - Required - Initial capacity hint for the dictionary. ### Returns A new, empty MultiDict object. ``` -------------------------------- ### MultiDict constructor Source: https://github.com/aio-libs/multidict/blob/master/docs/multidict.rst Creates a mutable multidict instance. Accepted parameters are the same as for dict, and if the same key appears several times it will be added. ```APIDOC ## MultiDict constructor ### Description Creates a mutable multidict instance. Accepted parameters are the same as for `dict`. If the same key appears several times it will be added. ### Method Constructor ### Signature `MultiDict(**kwargs)` `MultiDict(mapping, **kwargs)` `MultiDict(iterable, **kwargs)` ### Request Example ```python >>> d = MultiDict([('a', 1), ('b', 2), ('a', 3)]) >>> d ``` ``` -------------------------------- ### keys() and items() views Source: https://github.com/aio-libs/multidict/blob/master/docs/multidict.rst keys() view contains each key once, as spelled in its first item; items() shows every item. ```python >>> d = CIMultiDict([('X-Foo', '1'), ('x-foo', '2'), ('B', '3')]) >>> list(d.keys()) ['X-Foo', 'B'] >>> len(d.keys()), len(d) (2, 3) >>> list(d.items()) [('X-Foo', '1'), ('x-foo', '2'), ('B', '3')] ``` -------------------------------- ### MultiDict_GetCAPI() Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Imports the multidict C API capsule and returns a pointer to its function table. Returns NULL with an exception set on failure. ```APIDOC ## MultiDict_GetCAPI() ### Description Import the capsule and return a pointer to it, or `NULL` with an exception set on failure (for example if `multidict._multidict` could not be imported, or if the installed `multidict` provides an older, incompatible capsule version than this header requires – raised as `RuntimeError`). ### Method Function ### Endpoint `MultiDict_GetCAPI()` ### Returns - **MultiDict_CAPI\*** - Pointer to the capsule's function table, or `NULL` on failure. ### Usage Call this once, typically from the importing module's `Py_mod_exec` slot, and keep the returned pointer around for the lifetime of that module. ### Example ```c #include static int module_exec(PyObject *mod) { my_mod_state *state = PyModule_GetState(mod); state->capi = MultiDict_GetCAPI(); if (state->capi == NULL) { return -1; } return 0; } ``` ``` -------------------------------- ### Compile multidict extensions in debug mode Source: https://github.com/aio-libs/multidict/blob/master/README.rst Sets MULTIDICT_DEBUG_BUILD=1 to compile the extensions in debug mode for extension development. ```console $ MULTIDICT_DEBUG_BUILD=1 pip install multidict ``` -------------------------------- ### MultiDictProxy_New Source: https://github.com/aio-libs/multidict/blob/master/docs/cyapi.rst Creates a new proxy wrapping the given argument. ```APIDOC ## MultiDictProxy_New ### Description Creates a new proxy wrapping the given argument. ### Signature `MultiDictProxy_New(capi, arg) -> object` ### Parameters - **capi** - Required - The C API context. - **arg** - Required - The object to wrap. ### Returns A new proxy object. ``` -------------------------------- ### Using istr keys with CIMultiDict Source: https://github.com/aio-libs/multidict/blob/master/docs/multidict.rst Shows how to create an istr key explicitly and use it with CIMultiDict for case-insensitive lookups. The istr preserves original casing and compares like a regular str; case-insensitive matching is handled by CIMultiDict, not by istr equality. ```python >>> key = istr('Key') >>> key 'Key' >>> mdict = CIMultiDict(key='value') >>> key in mdict True >>> mdict[key] 'value' ``` -------------------------------- ### Check for exactly one Host header Source: https://github.com/aio-libs/multidict/blob/master/docs/multidict.rst When a key must carry exactly one value, as with security-sensitive HTTP headers such as Host, fetch every value with getall() and reject the input unless there is exactly one. ```python values = headers.getall('Host') if len(values) != 1: raise ValueError("expected exactly one Host header") host = values[0] ``` -------------------------------- ### MultiDictProxy_CheckExact(capi, op) -> bint Source: https://github.com/aio-libs/multidict/blob/master/docs/cyapi.rst Returns whether op is exactly a MultiDictProxy instance. This is a C API function that users can call directly. ```APIDOC ## MultiDictProxy_CheckExact(capi, op) -> bint ### Description Exact-type-only equivalent of `MultiDictProxy_Check`. Returns whether *op* is exactly an instance of the corresponding type. ### Parameters - **capi** - Required - The C API context. - **op** - Required - The object to check. ### Returns - **bint** - Boolean indicating exact type match. ``` -------------------------------- ### Re-sort spelling wordlist after editing Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md The wordlist must stay sorted case-insensitively; use this command after adding entries. -f puts CPython next to cchardet; LC_ALL=C keeps results consistent across machines. ```bash LC_ALL=C sort -f -o docs/spelling_wordlist.txt docs/spelling_wordlist.txt ``` -------------------------------- ### MultiDict_ForEach Source: https://github.com/aio-libs/multidict/blob/master/docs/cyapi.rst Low-level entry point to iterate over items in a MultiDict, with optional key filtering. It accepts a raw PyObject* key where NULL means visit all items, and uses a raw PyObject* visitor callback. ```APIDOC ## MultiDict_ForEach ### Description Low-level entry point to iterate over items in a MultiDict, with optional key filtering. It accepts a raw PyObject* key where NULL means visit all items, and uses a raw PyObject* visitor callback. ### Method C function ### Signature `MultiDict_ForEach(capi, self, key, visitor, user_data) except -1 -> Py_ssize_t` ### Parameters - **capi** - The C API object. - **self** - The MultiDict instance. - **key** (PyObject*) - Required - The key to filter by; pass NULL to visit all items. - **visitor** (MultiDict_ItemVisitor) - Required - Callback function of type `int (*)(void*, PyObject*, Py_hash_t, PyObject*, PyObject*)`. - **user_data** (void*) - Required - User data passed to the visitor. ### Return Value - **Py_ssize_t** - Number of items visited (>= 0) on success; -1 on error. ### Notes - The visitor must be declared with raw PyObject* parameters matching the typedef. - The visitor must not call back into any method on self while running. - The visitor returns a positive value to continue, 0 to stop early, or a negative value to abort with an exception set via PyErr_SetString. ``` -------------------------------- ### Reduce Callgrind instruction counts Source: https://github.com/aio-libs/multidict/blob/master/docs/benchmark.rst Formula used to reduce the four Valgrind child processes (run/noop at two round counts) into instructions per operation. Taking the difference between two non-zero round counts cancels interpreter startup; subtracting the second arm cancels the driving loop. ```python ir_per_op = ((run[r2] - run[r1]) - (noop[r2] - noop[r1])) / ((r2 - r1) * inner) ``` -------------------------------- ### MultiDict_ForEach Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Visits items of a MultiDict without building a list, optionally filtered by a key. The visitor callback is invoked for each matching entry, and the function returns the number of items visited. ```APIDOC ## MultiDict_ForEach ### Description Visits items of *self* without building a list. If *key* is `NULL`, calls *visitor* once for every `(key, value)` pair of *self*, in the same order `items()` would. If *key* is not `NULL`, calls *visitor* only for entries whose key equals *key* – the same values `getall()` would return, paired with *key* for a uniform callback signature; a missing key visits nothing, it is not an error. Returns the number of items visited (`>= 0`) on success, or `-1` with an exception set on failure. ### Method C function ### Signature `Py_ssize_t MultiDict_ForEach(MultiDict_CAPI *capi, PyObject *self, PyObject *key, MultiDict_ItemVisitor visitor, void *user_data)` ### Parameters - **capi** (MultiDict_CAPI*) - Required - Pointer to the MultiDict C API structure. - **self** (PyObject*) - Required - The MultiDict instance to iterate. Must be a `MultiDict`, `CIMultiDict`, `MultiDictProxy`, or `CIMultiDictProxy` instance. - **key** (PyObject*) - Optional - If not `NULL`, only entries with this key are visited. - **visitor** (MultiDict_ItemVisitor) - Required - Callback function to invoke for each visited item. - **user_data** (void*) - Required - User-provided data passed to the visitor. ### Return Value - **Py_ssize_t** - Number of items visited (`>= 0`) on success, or `-1` with an exception set on failure. ### Thread Safety Safe for concurrent use on the same object. The whole walk, including every *visitor* call, runs under *self*’s internal critical section. ### Visitor Callback `typedef int (*MultiDict_ItemVisitor)(void *user_data, PyObject *identity, Py_hash_t hash, PyObject *key, PyObject *value)` - **user_data** (void*) - User-provided data. - **identity** (PyObject*) - The entry’s canonical key (the key itself for `MultiDict`, the internal lower-cased form for `CIMultiDict`). Borrowed reference. - **hash** (Py_hash_t) - The hash of *identity*. - **key** (PyObject*) - The entry’s key. Borrowed reference. - **value** (PyObject*) - The entry’s value. Borrowed reference. Return a positive value to keep the walk going, `0` to stop early (not an error), or a negative value to abort with an error (a Python exception must already be set). ### Notes - *visitor* must not call back into any method on *self* while running. The walk executes under one internal lock and raises a `RuntimeError` if a reentrant mutation changes the version. ``` -------------------------------- ### pop(key) Source: https://github.com/aio-libs/multidict/blob/master/docs/multidict.rst An alias to popone(). Only the first occurrence is removed. ```APIDOC ## pop(key) ### Description An alias to `popone()`. Only the **first** occurrence is removed. ### Method pop ### Parameters - **key** - The key to remove ``` -------------------------------- ### MultiDict_New Source: https://github.com/aio-libs/multidict/blob/master/docs/cyapi.rst Creates a new multidict object using the given C API pointer. The Cython wrapper matches the C counterpart's failure semantics. ```APIDOC ## MultiDict_New ### Description Creates a new multidict object using the given C API pointer. The Cython wrapper matches the C counterpart's failure semantics. ### Method Cython function ### Signature `MultiDict_New(capi, ...)` ### Parameters - `capi` (MultiDict_CAPI*) - Required - Pointer to the C API capsule - Additional arguments as per C API ### Returns - New multidict object ### Exceptions - As per C counterpart ``` -------------------------------- ### setdefault(key) Source: https://github.com/aio-libs/multidict/blob/master/docs/multidict.rst Returns the first value for a key if it exists, otherwise inserts the key with a default value and returns that default. The default defaults to None. ```APIDOC ## setdefault(key) ### Description If *key* is in the dictionary, return its the **first** value. If not, insert *key* with a value of *default* and return *default*. *default* defaults to `None`. ### Parameters - **key** - Required - The key to look up or insert. - **default** - Optional - Value to insert and return if key not found. Defaults to `None`. ### Returns - The first value for the key, or *default* if key was not present. ``` -------------------------------- ### MultiDict_CheckExact(capi, op) -> bint Source: https://github.com/aio-libs/multidict/blob/master/docs/cyapi.rst Returns whether op is exactly a MultiDict instance. This is a C API function that users can call directly. ```APIDOC ## MultiDict_CheckExact(capi, op) -> bint ### Description Exact-type-only equivalent of `MultiDict_Check`. Returns whether *op* is exactly an instance of the corresponding type. ### Parameters - **capi** - Required - The C API context. - **op** - Required - The object to check. ### Returns - **bint** - Boolean indicating exact type match. ``` -------------------------------- ### MultiDict_GetCAPI Source: https://github.com/aio-libs/multidict/blob/master/docs/cyapi.rst Imports the multidict C API capsule and returns a pointer to it. Raises RuntimeError on failure, including version mismatch. ```APIDOC ## MultiDict_GetCAPI ### Description Imports the multidict C API capsule and returns a pointer to it. Raises RuntimeError on failure, including version mismatch. ### Method Cython function ### Signature `MultiDict_GetCAPI() except NULL` ### Returns - Pointer to `MultiDict_CAPI` struct ### Exceptions - `RuntimeError` - raised on failure (including version mismatch) ``` -------------------------------- ### CIMultiDictProxy_GetType Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Returns a new reference to the CIMultiDictProxy type object. ```APIDOC ## CIMultiDictProxy_GetType ### Description Returns a new reference to the CIMultiDictProxy type object. ### Signature ```c PyTypeObject *CIMultiDictProxy_GetType(MultiDict_CAPI *capi) ``` ### Parameters - `capi` (MultiDict_CAPI*) - Required - Pointer to the C API structure. ### Return Value - `PyTypeObject*` - A new reference to the CIMultiDictProxy type object. ### Thread Safety Atomic. ``` -------------------------------- ### CIMultiDictProxy_CheckExact(capi, op) -> bint Source: https://github.com/aio-libs/multidict/blob/master/docs/cyapi.rst Returns whether op is exactly a CIMultiDictProxy instance. This is a C API function that users can call directly. ```APIDOC ## CIMultiDictProxy_CheckExact(capi, op) -> bint ### Description Exact-type-only equivalent of `CIMultiDictProxy_Check`. Returns whether *op* is exactly an instance of the corresponding type. ### Parameters - **capi** - Required - The C API context. - **op** - Required - The object to check. ### Returns - **bint** - Boolean indicating exact type match. ``` -------------------------------- ### Symlink for dual issue and PR fragment resolution Source: https://github.com/aio-libs/multidict/blob/master/AGENTS.md When both an issue and a PR number are in play, keep the issue-numbered file as the real fragment and add a symlink at CHANGES/..rst pointing to it. This ensures towncrier and GitHub cross-references both find the entry. ```bash ln -s 1284.bugfix.rst CHANGES/1340.bugfix.rst ``` -------------------------------- ### MultiDict_GetVersion Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Returns the version counter of a MultiDict, CIMultiDict, MultiDictProxy, or CIMultiDictProxy instance. The version changes on every mutation of the instance. ```APIDOC ## MultiDict_GetVersion ### Description Returns the version counter of a MultiDict, CIMultiDict, MultiDictProxy, or CIMultiDictProxy instance. The version changes on every mutation of the instance. ### Signature ```c uint64_t MultiDict_GetVersion(MultiDict_CAPI *capi, PyObject *self) ``` ### Parameters - `capi` (MultiDict_CAPI*) - Required - Pointer to the C API structure. - `self` (PyObject*) - Required - The MultiDict, CIMultiDict, MultiDictProxy, or CIMultiDictProxy instance. ### Return Value - `uint64_t` - The version counter. Returns 0 on error; check `PyErr_Occurred()` to distinguish from a valid version of 0. ### Thread Safety Atomic. Lock-free relaxed read of the version counter. ### Errors Raises `TypeError` if `self` is not a valid instance type. ``` -------------------------------- ### keys() Source: https://github.com/aio-libs/multidict/blob/master/docs/multidict.rst Returns a new view of the dictionary's keys. Each key appears once, as spelled in its first item. ```APIDOC ## keys() ### Description Return a new view of the dictionary's keys. View contains each key once, as spelled in its first item. ### Method keys ### Request Example ```python >>> d = CIMultiDict([('X-Foo', '1'), ('x-foo', '2'), ('B', '3')]) >>> list(d.keys()) ['X-Foo', 'B'] >>> len(d.keys()), len(d) (2, 3) ``` ``` -------------------------------- ### getone(key) Source: https://github.com/aio-libs/multidict/blob/master/docs/multidict.rst Returns the first value for key if key is in the dictionary, else default. Raises KeyError if default is not given and key is not found. ```APIDOC ## getone(key) ### Description Return the **first** value for *key* if *key* is in the dictionary, else *default*. Raises `KeyError` if *default* is not given and *key* is not found. ### Method getone ### Parameters - **key** - The key to look up ``` -------------------------------- ### MultiDict_WatchEvent Source: https://github.com/aio-libs/multidict/blob/master/docs/index.rst Enumeration of events that can be watched on a multidict. ```APIDOC ## MultiDict_WatchEvent ### Description Enumeration of events that can be watched on a multidict. ### Method C API enum ### Values - `MultiDict_EVENT_ADDED` - A key-value pair was added. - `MultiDict_EVENT_REPLACED` - A value was replaced. - `MultiDict_EVENT_DELETED` - A key was deleted. - `MultiDict_EVENT_CLEARED` - The multidict was cleared. - `MultiDict_EVENT_CLONED` - The multidict was cloned. - `MultiDict_EVENT_DEALLOCATED` - The multidict was deallocated. - `MultiDict_EVENT_BATCH_BEGIN` - A batch operation began. - `MultiDict_EVENT_BATCH_END` - A batch operation ended. - `MultiDict_EVENT_LOST` - A watcher was lost. ``` -------------------------------- ### MultiDictProxy_GetType Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Returns a new reference to the MultiDictProxy type object. ```APIDOC ## MultiDictProxy_GetType ### Description Returns a new reference to the MultiDictProxy type object. ### Signature ```c PyTypeObject *MultiDictProxy_GetType(MultiDict_CAPI *capi) ``` ### Parameters - `capi` (MultiDict_CAPI*) - Required - Pointer to the C API structure. ### Return Value - `PyTypeObject*` - A new reference to the MultiDictProxy type object. ### Thread Safety Atomic. ``` -------------------------------- ### CIMultiDict_New Source: https://github.com/aio-libs/multidict/blob/master/docs/cyapi.rst Creates a new, empty CIMultiDict instance. ```APIDOC ## CIMultiDict_New ### Description Creates a new, empty CIMultiDict instance. ### Signature `CIMultiDict_New(capi, prealloc_size) -> object` ### Parameters - **capi** - Required - The C API context. - **prealloc_size** - Required - Initial capacity hint for the dictionary. ### Returns A new, empty CIMultiDict object. ``` -------------------------------- ### MultiDictProxy_Check(capi, op) -> bint Source: https://github.com/aio-libs/multidict/blob/master/docs/cyapi.rst Returns whether op is an instance of MultiDictProxy or a subclass. This is a C API function that users can call directly. ```APIDOC ## MultiDictProxy_Check(capi, op) -> bint ### Description Returns whether *op* is an instance of the corresponding type or a subclass. ### Parameters - **capi** - Required - The C API context. - **op** - Required - The object to check. ### Returns - **bint** - Boolean indicating instance or subclass match. ``` -------------------------------- ### CIMultiDictProxy_New Source: https://github.com/aio-libs/multidict/blob/master/docs/cyapi.rst Creates a new proxy wrapping the given argument. ```APIDOC ## CIMultiDictProxy_New ### Description Creates a new proxy wrapping the given argument. ### Signature `CIMultiDictProxy_New(capi, arg) -> object` ### Parameters - **capi** - Required - The C API context. - **arg** - Required - The object to wrap. ### Returns A new proxy object. ``` -------------------------------- ### Import capsule in module_exec with MultiDict_GetCAPI() Source: https://github.com/aio-libs/multidict/blob/master/docs/capi.rst Call MultiDict_GetCAPI() once, typically from the importing module's Py_mod_exec slot, and keep the returned pointer around for the module's lifetime. Returns NULL with an exception set on failure, e.g., if multidict._multidict could not be imported or the capsule version is incompatible. ```c #include static int module_exec(PyObject *mod) { my_mod_state *state = PyModule_GetState(mod); state->capi = MultiDict_GetCAPI(); if (state->capi == NULL) { return -1; } return 0; } ```