I am writing a python model for heavy calculations in rust using the pyo3 bindings. However, for a rust struct with a variable containing an empty list I cannot append to that variable in python.
Does anybody know how to do this? See below for a MWE ( that I cannot get to work ):
I have a rust file called lib.rs:
// lib.rs
use pyo3::prelude::*;
use std::vec::Vec;
#[pyclass(subclass)]
pub struct TestClass {
#[pyo3(get)]
pub id: i32,
#[pyo3(get, set)]
pub test_list: Vec<f32>
}
#[pymethods]
impl TestClass {
#[new]
pub fn new(id: i32) -> TestClass {
TestClass{
id,
test_list: Vec::new()
}
}
}
/// A Python module implemented in Rust.
#[pymodule]
fn test_rust(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<TestClass>()?;
Ok(())
}
This library is build using the maturin
package. When I initiate the TestClass
in python that works as expected. However, when I want to append to the class attribute test_list
this is not happening. test_list
still is an empty list. See for an example below:
from test_rust import TestClass
foo = TestClass(1)
print(foo.test_list) # output: []
foo.test_list.append(2.3)
print(foo.test_list) # output: [] - expected: [2.3]
The pyo3 documentation stated that the types Vec<T>
and list[T]
are accepted. However, this does not work.
Any help would be very much appreciated.