I'm using pyo3 in Rust to create a Python module. I can create a class, and a constructor with:
#[pyclass]
struct MyClass {
i: u8,
}
#[pymethods]
impl MyClass {
#[new]
fn new() -> PyResult<Self> {
println!("Instance Constructed!");
Ok(MyClass { i: 0 })
}
// Doesn't work
fn __del__(&mut self) {
println!("Instance destroyed");
}
}
#[pymodule]
fn myclass(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<MyClass>()?;
Ok(())
}
When I compile it, and use my class from Python, I can see that my instance has a __del__
method, and I can call it manually, but Python won't call it when the instance is being destroyed:
>>> from myclass import MyClass
>>> inst = MyClass()
Instance Constructed!
>>> inst.__del__
<built-in method __del__ of builtins.MyClass object at 0x766ca4c0>
>>> inst.__del__()
Instance destroyed
>>> del(inst)
>>>
Is there a special way to create a destructor in Rust using pyo3?
Why would Python not call __del__
? It seems to have no problems calling it for a class defined in pure Python when you del
the instance.