Skip to content

Ergonomic API around capsules#5983

Open
Tpt wants to merge 1 commit intoPyO3:mainfrom
Tpt:tpt/capsule
Open

Ergonomic API around capsules#5983
Tpt wants to merge 1 commit intoPyO3:mainfrom
Tpt:tpt/capsule

Conversation

@Tpt
Copy link
Copy Markdown
Contributor

@Tpt Tpt commented Apr 17, 2026

  • A trait PyCapsuleType to give the capsule name for the type and encode that the type is pycapsule-safe
  • Two wrapper types PyCapsuleValue and PyCapsuleValueRef that implement FromPyObject and IntoTypeObject wrapping respectively T and &T

Example of API goal:

#[pyfunction]
fn add_one(foo: PyCapsuleValueRef<'_, Foo>) -> PyCapsuleValue<Foo> {
    PyCapsuleValue(Foo { val: foo.val })
}

- A trait `PyCapsuleType` to give the capsule name for the type and encode that the type is pycapsule-safe
- Two wrapper types `PyCapsuleValue` and `PyCapsuleValueRef` that implement `FromPyObject` and `IntoTypeObject` wrapping respectively T and &T

Example of API goal:
```rust
#[pyfunction]
fn add_one(foo: PyCapsuleValueRef<'_, Foo>) -> PyCapsuleValue<Foo> {
    PyCapsuleValue(Foo { val: foo.val })
}
```
@Tpt Tpt marked this pull request as ready for review April 20, 2026 07:06
@ngoldbaum
Copy link
Copy Markdown
Contributor

Just out of curiosity, why would someone want this? My understanding is that the PyCapsule API is there to serve use-cases like NumPy's C API where someone wants to expose a C API for a Python library that must be imported before it can be usable from C. Are you trying to enable a similar pattern with PyO3 or something else entirely?

@Tpt
Copy link
Copy Markdown
Contributor Author

Tpt commented Apr 23, 2026

@ngoldbaum Yes! This is this kind of usecases. For example datafusion Python bindings relies a lot on capsule for extensibilities and method definition like:

    pub fn __datafusion_table_provider__<'py>(
        &self,
        py: Python<'py>,
        session: Bound<PyAny>,
    ) -> PyResult<Bound<'py, PyCapsule>> {

can become

    pub fn __datafusion_table_provider__(
        &self,
        session: PyCapsuleValueRef<'_, FFI_LogicalExtensionCodec>,
    ) -> PyResult<PyCapsuleValue<FFI_TableProvider>> {

@ngoldbaum
Copy link
Copy Markdown
Contributor

Ah, TIL there's an Arrow PyCapsule interface: https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants