-
Let's say I have a function like below. It replaces the character #[pyfunction]
fn replace_a_with_b(py: Python, value: &Bound<'_, PyAny>) -> PyObject {
if let Ok(string) = value.extract::<String>() {
return string.replace('a', "b").to_object(py);
}
if let Ok(iter) = value.clone().downcast_into::<PyList>() {
return iter
.iter()
.map(|x| replace_a_with_b(py, x.as_ref()).to_object(py))
.collect::<Vec<PyObject>>()
.to_object(py);
}
value.to_object(py)
} How do I port this code to |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Ah okay I found some methods that weren't clear to me from the migration guide and now I have this: #[pyfunction]
fn replace_a_with_b(py: Python, value: &Bound<'_, PyAny>) -> PyObject {
if let Ok(string) = value.extract::<String>() {
return string.replace('a', "b").into_pyobject(py).unwrap().into();
}
if let Ok(iter) = value.clone().downcast_into::<PyList>() {
return iter
.iter()
.map(|x| {
replace_a_with_b(py, x.as_ref())
.into_pyobject(py)
.unwrap()
.into()
})
.collect::<Vec<PyObject>>()
.into_pyobject(py)
.unwrap()
.into();
}
value.into_bound_py_any(py).unwrap().into()
} is that how you're supposed to do this? It seems a bit convoluted. |
Beta Was this translation helpful? Give feedback.
I was able to refactor to this:
There's two main changes I made here: