Question: function overriding doesn't seem to work in python #1917
-
Hello, I have a framework in python, now I want to rewrite it in rust using pyo3. The framework has a Base class for users to inherent, in the child class, a user would provide implementation for a function "do_work". And my framework (the base class) will call that "do_work" function. But the same paradigm doesn't seem to work with pyo3 I have the following in rust: #[pyclass(subclass)]
struct MyClass {
num: i32,
debug: bool,
}
#[pymethods]
impl MyClass {
#[new]
fn new() -> Self {
MyClass { num:32, debug: false }
}
#[classmethod]
fn print_test(cls: &PyType) -> PyResult<i32> {
println!("print from rust: {}", 23);
let gil = Python::acquire_gil();
let py = gil.python();
cls.call_method("override_test", (), None);
Ok(32)
}
#[classmethod]
fn override_test(cls: &PyType) -> PyResult<i32> {
println!("print within rust");
Ok(600)
}
} and this in python class Test(testbed.MyClass):
def __init__(self):
self.debug = 32
testbed.MyClass.__init__(self)
def override_test(self):
print("print within python")
self.debug = 43
return 453
demo = Test()
demo.print_test()
print("test result: ", demo.debug ) If I don't provide override_test in the child class "Test", things would work as expected. I would see But if I provide an overriden function in the child class, this overriden function won't be called by the rust parent class. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
Hi, there's two problems with your snippet above:
If I add
Then I get this output from the Python script:
... which is a crash caused by the second error. |
Beta Was this translation helpful? Give feedback.
-
Thank you! I now know the issue. but I still can't make it to work, because in the rust function #[pymethods]
impl MyClass {
#[new]
fn new() -> Self {
MyClass { num:32, debug: false }
}
fn print_test(&self, py: Python) -> PyResult<i32> {
println!("print from rust: {}", 23);
let gil = Python::acquire_gil();
let py = gil.python();
//I'm not sure what I should do here?
//self.call_method("override_test", (), None)?;
self.override_test(); // doesn't trigger the overriden function
Ok(32)
}
fn override_test(&self) -> PyResult<i32> {
println!("print within rust");
Ok(600)
}
}
|
Beta Was this translation helpful? Give feedback.
-
Try this:
|
Beta Was this translation helpful? Give feedback.
-
that worked like a charm! thank you! |
Beta Was this translation helpful? Give feedback.
Hi, there's two problems with your snippet above:
cls.call_method
. The compiler is even warning you this:classmethod
.If I add
?
at the end ofcls_call_method(...)?;
, so that the error is correctly propagated, so theprint_test
function looks like this: