Rust Pyo3 bindings: How to reuse python methods on Generic rust types

Viewed 593

I've got a problem a bit more complicated than this. But I think this breaks it down. I have some generic struct, which has three constructors to get a concrete typed struct. They all have the same generic methods, except for the constructors. What I want is something like this:

use pyo3::prelude::*;

#[pyclass]
struct AnyVec<T> {
    vec_: Vec<T>,
}

// General methods which
#[pymethods]
impl<T> AnyVec<T> {
    fn push(&mut self, v: T) {
        self.vec_.push(v)
    }

    fn pop(&mut self, v: T) -> T {
        self.vec_.pop()
    }
}

#[pymethods]
impl AnyVec<String> {
    #[new]
    fn new() -> Self {
        AnyVec { vec_: vec![] }
    }
}

#[pymethods]
impl AnyVec<f32> {
    #[new]
    fn new() -> Self {
        AnyVec { vec_: vec![] }
    }
}

When I try to compile this. pyo3 warns me that it cannot use generics. error: #[pyclass] cannot have generic parameters.

Is it possible to create some sort of generic base class from which the concrete types inherit?.

For completion; here is my Cargo.toml:

[package]
name = "example"
edition = "2018"

[dependencies]
pyo3 = { version="0.9.0-alpha.1", features = ["extension-module"] }

[lib]
name = "example"
crate-type = ["cdylib"]
0 Answers
Related