Skip to content

How to migrate functions that take an Bound<'_, PyAny> and output PyObject to 0.23.0? #4826

Answered by LilyFoote
evroon asked this question in Questions
Discussion options

You must be logged in to vote

I was able to refactor to this:

use pyo3::conversion::IntoPyObjectExt;
use pyo3::prelude::*;
use pyo3::types::PyList;

#[pyfunction]
fn replace_a_with_b<'py>(
    py: Python<'py>,
    value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
    if let Ok(string) = value.extract::<String>() {
        return Ok(string.replace('a', "b").into_pyobject(py)?.into_any());
    }

    if let Ok(iter) = value.downcast::<PyList>() {
        return iter
            .iter()
            .map(|x| replace_a_with_b(py, x.as_ref()))
            .collect::<PyResult<Vec<Bound<'_, PyAny>>>>()?
            .into_pyobject(py);
    }

    value.into_bound_py_any(py)
}

There's two main changes I made here:

  1. C…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@LilyFoote
Comment options

Answer selected by evroon
@evroon
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants