I want to run a cleanup method in a class (pyo3) when Python exits.
The code is as follows:
fn register_at_exit(&self, py: Python) -> PyResult<()> {
let fun: Py<PyAny> = PyModule::import_bound(py, "atexit")?.getattr("register")?.into();
let closure = |
args: &Bound<'_, PyTuple>,
_kwargs: Option<&Bound<'_, PyDict>>
| -> PyResult<()> {
self.instance.shutdown(None);
Ok(())
};
let cbfunc = PyCFunction::new_closure_bound(py, None, None, closure)?;
let _ = fun.call1(py, (cbfunc,))?;
Ok(())
}
The problem is that new_closure_bound
only accepts an Fn
type function, but the closure is an FnMut
, because the containing function call self.instance.shutdown(None)
is an FnMut
.