PyO3 / pyo3

Rust bindings for the Python interpreter
https://pyo3.rs
Apache License 2.0
12k stars 741 forks source link

`Cow` equivalent in PyO3 #3839

Open cmpute opened 7 months ago

cmpute commented 7 months ago

I propose to add a type to support copy-on-write behavior just like the std::borrow::Cow. The Cow type in std is usually unwanted because a reference to a Python object is held though PyRef. Therefore something like the following will be useful:

enum PyCow<'a, B>
where
    B: 'a + ToOwned + PyClass,
{
    Borrowed(PyRef<'a, B>),
    Owned(<B as ToOwned>::Owned),
}

This is useful when a function accepts both a Python object or something that can be converted to the object. For example, if I have a rust-implemented Python-type Decimal, a function that accepts a either Decimal or a string can take this as input to prevent a copy.

(Not sure if this is useful for other people, or if it's compatible with the new Bound API or not... Just post the idea here for discussion)

davidhewitt commented 7 months ago

I think there is definitely space for this kind of idea, and it is strongly related to what we just added in #3802 . There's a lot of unresolved questions in my head about this, though.

Folks willing to explore this idea further are very welcome, whether it gets merged immediately into pyo3 or we allow time for this idea to mature as a separate crate, I can see potential in it.