Reuse Python bindings defined in one crate in another one with Python bindgings #2340
Replies: 3 comments 12 replies
-
I think the problem is that both extensions are separate DSO and therefore do not share their static variables. PyO3 uses static variables to cache type objects with a stable identify which is then compared in e.g. This would imply that re-use is limited to statically linked Rust code (and possibly re-exporting Python end points), but not re-use as separately linked extensions. (I am not sure if it would be viable to have the loader deduplicate these statics but it would certainly be complicated by the possibility of incompatible versions of PyO3 being used by different extension modules.) |
Beta Was this translation helpful? Give feedback.
-
I just found the following solution: use As a more concrete example, I want to "re-export" the Note: none of what's here requires changing anything in the external crates. Hence, after running [package]
name = "pyarrowrs"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "pyarrowrs"
crate-type = ["cdylib"]
[dependencies]
pyo3 = { version = "0.17.3", features = ["extension-module"]}
hifitime = {version = "3.8.0", features = ["python"]} # Enables the Python bindings in hifitime Now, in use hifitime::prelude::*;
use pyo3::prelude::*;
#[derive(Clone, Copy, Debug)]
#[repr(C)]
#[pyclass]
pub struct CustomDuration {
pub(crate) centuries: i16,
pub(crate) nanoseconds: u64,
}
#[pymodule]
fn pyarrowrs(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<Epoch>()?;
m.add_class::<TimeScale>()?;
m.add_class::<TimeSeries>()?;
m.add_class::<Duration>()?;
m.add_class::<Unit>()?;
m.add_class::<CustomDuration>()?; // This is the only structure that is defined in this crate, everything else is from `hifitime::prelude`
Ok(())
}
#[test]
fn test_main() {
assert_eq!(1 + 1, 2);
} Build a develop version with
And run!
As you see, all of the classes from |
Beta Was this translation helpful? Give feedback.
-
It might worth to check how other library implements this: pybind/pybind11#616, Cython's |
Beta Was this translation helpful? Give feedback.
-
TL/DR: is it possible to reuse pyo3 classes exposed in one library in another one?
like having one Rust crate with python bindings and after that use it as a dependency in another crate (which will have its own Python bindings) and reuse Python classes from the first one in it?
Here is the project with README to reproduce the error
https://github.com/lycantropos/pyo3-reuse-bindings
So how to do that? By some sort of linkage with installed dynamic library in
site-packages
?Beta Was this translation helpful? Give feedback.
All reactions