Skip to content

CAPI Draft - #1183

Closed
asvetlov wants to merge 22 commits into
masterfrom
capi
Closed

asvetlov wants to merge 22 commits into
masterfrom
capi

Conversation

@asvetlov

@asvetlov asvetlov commented Jun 19, 2025 •

Copy link
Copy Markdown
Member

No description provided.

@asvetlov

Copy link
Copy Markdown
Member Author

The PR contains a draft for CAPI with tests.

For now, only a minimal subset of functions is exposed, just for the idea demonstration.
Cython bindings are to be done, they are built on top of C API anyway.

Tests are attached.

@Vizonex, you might be interested in the PR. It is based on your work, but it is slightly different in implementation details.

@@ -0,0 +1,4 @@
try:
from testcapi._api import * # noqa
except ImportError:

Check notice

Code scanning / CodeQL

Empty except

'except' clause does nothing but pass and there is no explanatory comment.

Copilot Autofix

AI over 1 year ago

To fix the issue, we should add a comment explaining why the exception is being ignored or handle the exception in a meaningful way. The best approach is to log the exception using Python's logging module, which provides a lightweight way to record the failure without interrupting the program's execution. This ensures that the failure is documented and can be debugged later if necessary.

Suggested changeset 1
testcapi/testcapi/__init__.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/testcapi/testcapi/__init__.py b/testcapi/testcapi/__init__.py
--- a/testcapi/testcapi/__init__.py
+++ b/testcapi/testcapi/__init__.py
@@ -1 +1,3 @@
+import logging
+
 try:
@@ -3,2 +5,2 @@
 except ImportError:
-    pass
+    logging.warning("Failed to import testcapi._api. Some functionality may be unavailable.")
EOF
@@ -1 +1,3 @@
import logging

try:
@@ -3,2 +5,2 @@
except ImportError:
pass
logging.warning("Failed to import testcapi._api. Some functionality may be unavailable.")
Copilot is powered by AI and may make mistakes. Always verify output.
@codecov

codecov Bot commented Jun 19, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 3.00752% with 129 lines in your changes missing coverage. Please review.
✅ Project coverage is 96.32%. Comparing base (e0e61c2) to head (636f265).
⚠️ Report is 107 commits behind head on master.

Files with missing lines Patch % Lines
tests/test_capi.py 3.00% 129 Missing ⚠️

❌ Your patch check has failed because the patch coverage (3.00%) is below the target coverage (95.00%). You can increase the patch coverage or adjust the target coverage.
❌ Your project check has failed because the head coverage (95.28%) is below the target coverage (100.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1183      +/-   ##
==========================================
- Coverage   99.85%   96.32%   -3.54%     
==========================================
  Files          26       27       +1     
  Lines        3510     3643     +133     
  Branches      252      252              
==========================================
+ Hits         3505     3509       +4     
- Misses          3      132     +129     
  Partials        2        2              
Flag Coverage Δ
CI-GHA 96.32% <3.00%> (-3.54%) ⬇️
pytest 96.32% <3.00%> (-3.54%) ⬇️

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.

@codspeed

codspeed Bot commented Jun 19, 2025 •

Copy link
Copy Markdown

CodSpeed Performance Report

Merging #1183 will not alter performance

Comparing capi (636f265) with master (e0e61c2)

Summary

✅ 245 untouched benchmarks

@webknjaz webknjaz left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The full-blown packaging setup seems like huge overengineering. There's better ways to integrate with pytest that wouldn't require additional layers of complexity.

Comment thread testcapi/setup.cfg Resolved
@asvetlov

Copy link
Copy Markdown
Member Author

The full-blown packaging setup seems like huge overengineering. There's better ways to integrate with pytest that wouldn't require additional layers of complexity.

Sorry, I don't follow your idea.

  1. We need a compiled package for testing C (and later Cython) APIs.
  2. This package shouldn't be a part of multidict itself; it is required for testing only, and multidict should already be installed for compiling the test helper.

If you have a better idea, please don't hesitate to push a working code to show your thoughts.

@Vizonex

Vizonex commented Jun 20, 2025

Copy link
Copy Markdown
Member

The full-blown packaging setup seems like huge overengineering. There's better ways to integrate with pytest that wouldn't require additional layers of complexity.

Sorry, I don't follow your idea.

  1. We need a compiled package for testing C (and later Cython) APIs.
  2. This package shouldn't be a part of multidict itself; it is required for testing only, and multidict should already be installed for compiling the test helper.

If you have a better idea, please don't hesitate to push a working code to show your thoughts.

@asvetlov I agree with you since I spent more time than I originally anticipated trying to expose multidict's inner workings and I seem to keep having to second-guess does this go here or does this go here? At the end of the day the unpredictability of some parts of the CAPI needs a better foundation. I am willing to drop my things for a second time and just work on helping you get this passed a second time. At the end of the day. The practice I get from doing this has paid off for me in the long-run and I seem to be learning new stuff the deeper I've dived into this.

I don't even feel upset at all about dropping older pull requests since I seem to keep learning new stuff. I am actually ok with closing #1178 and moving to this pull request so that we can develop a safer implementation to use. I'll hold onto a copy of my old pull request in my folders incase I need to utilize some of it's information later.

@Vizonex

Vizonex commented Jun 20, 2025

Copy link
Copy Markdown
Member

@asvetlov I'm forking your draft instead since it has a better foundation to work upon the only thing I could see being a problem is the api calls for the capsule to be a little bit too generic since you never know if someone plans to compile this CAPI with another capsuled module. The last thing you would want is for someone to end up using the same names and colliding with it when compiling everything.

@asvetlov

Copy link
Copy Markdown
Member Author

@Vizonex, your work is very valuable.
I've borrowed many ideas from your PRs, let's finish the work together.
I'll review #1185 soon, thank you for it!

@Vizonex

Vizonex commented Jun 21, 2025

Copy link
Copy Markdown
Member

@Vizonex, your work is very valuable. I've borrowed many ideas from your PRs, let's finish the work together. I'll review #1185 soon, thank you for it!

Your welcome. I seem to be learning new stuff as I am doing this.

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Jun 22, 2025
@Vizonex

Vizonex commented Jun 22, 2025

Copy link
Copy Markdown
Member

@asvetlov Crap I just remembered I deleted my old fork I still have the code on hand and we can quickly remerge it and resume where I left off my bad. The accidental merge confused me :/

@asvetlov

Copy link
Copy Markdown
Member Author

@Vizonex here is my local copy of your branch; you can use it on your own.

Sorry again; I unintentionally pushed your branch with code reformatting in the command line, but the target was my branch. GitHub processed it as a merge. git sometimes allows dangerous things :(

@asvetlov asvetlov mentioned this pull request Jun 22, 2025
3 tasks done
@Vizonex

Vizonex commented Jun 28, 2025

Copy link
Copy Markdown
Member

@asvetlov Let me write some more API Functions now that I know that you've merged my things.

@Vizonex

Vizonex commented Jun 28, 2025

Copy link
Copy Markdown
Member

@asvetlov I made a copy of my old branch and archived it to https://github.com/Vizonex/multidict/tree/vizonex-capi so that I could resync my branch with yours again. You can use it as a reference if we need to later but let me go ahead and resync with your changes first.

@Vizonex

Vizonex commented Jun 30, 2025

Copy link
Copy Markdown
Member

No Idea how we should go about implementing CIMultiDict and CIMultiDictProxy but now I have done everything else.

@asvetlov

Copy link
Copy Markdown
Member Author

Superseded by #1480

@asvetlov asvetlov closed this Sep 22, 2026
asvetlov added a commit that referenced this pull request Sep 23, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Adds a public C API capsule (`multidict._multidict.CAPI`, reached
through `multidict_capi.h` / `multidict_capi_struct.h`) so other C
extensions can create and manipulate `MultiDict`, `CIMultiDict`,
their proxies, and `istr` directly, without going through the
Python-level API. Covers type checks and constructors for all four
mapping types plus `istr`, `getversion()` and `len()`, and
`add()`, `clear()`, `setdefault()`, and single-item access (`in`,
`[]`, `del`, `pop()`) for the mutable types. `GetItem`, `Pop`, and
`SetDefault` follow the `PyDict_GetItemRef` / `PyDict_SetDefaultRef`
design, reporting a missing key through the return code rather than
an exception. `MultiDict_ForEach` visits every item, or just the
items for one key, through a callback, without allocating a list.

The same capsule is also reachable from Cython: `multidict/__init__.pxd`
lets third-party Cython code `cimport multidict`, mirrored by a
`multidict/_testcyapi.pyx` test harness. Cython is optional and never
a real dependency of `multidict` itself; an ordinary or release build
never sees it, and a dedicated CI job exercises the opt-in path.

## Are there changes in behavior for the user?

No behavior change for existing Python-level usage. This adds a new,
opt-in C API surface for other C extensions and Cython code to use.

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

The struct only ever grows at the end, so older clients keep working
against newer `multidict` builds. The Cython binding is test-only and
opt-in, so it adds no ongoing dependency burden.

## Related issue number

Supersedes and closes #1183, #1190, #1191 (earlier C API drafts).

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt`
- [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>

Tests: `pytest -q` on both the accelerated build (with and without the
Cython opt-in) and the pure-Python build (`MULTIDICT_NO_EXTENSIONS=1`);
`tests/test_capi.py`'s `api` fixture runs every case against both the
C and Cython bindings when Cython is opted in.
Lint: `pre-commit run --all-files` (ruff, mypy for 3.13/3.11, yamllint,
clang-format, GitHub Actions validators) clean.
Docs: strict Sphinx HTML build and `doc-spelling` clean.

Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.
</details>

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
@webknjaz
webknjaz deleted the capi branch September 25, 2026 18:47
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.

4 participants