PyO3 and String argument

Next in a row PyO3 question ...

This compiles:

#[pyfunction]
fn demo(line: String)  {
}

but this doesn't:

#[pyclass]
#[derive(Clone)]
pub struct Data;

#[pymethods]
impl Data {
    pub fn demo(line: String)  {
    }
}

Why? The error is:

error[E0277]: the trait bound `String: From<&PyCell<Data>>` is not satisfied
  --> src/lib.rs:23:23
   |
23 |     pub fn demo(line: String)  {
   |                       ^^^^^^ the trait `From<&PyCell<Data>>` is not implemented for `String`
   |
   = help: the following other types implement trait `From<T>`:
             <String as From<&String>>
             <String as From<&mut str>>
             <String as From<&str>>
             <String as From<Box<str>>>
             <String as From<Cow<'a, str>>>
             <String as From<char>>
   = note: required because of the requirements on the impl of `Into<String>` for `&PyCell<Data>`
   = note: required because of the requirements on the impl of `TryFrom<&PyCell<Data>>` for `String`

You must either annotate demo with #[staticmethod] or provide an argument &self:

use pyo3::{pyclass, pymethods};

#[pyclass]
#[derive(Clone)]
pub struct Data;

#[pymethods]
impl Data {
    pub fn demo(&self, line: String) {}

    #[staticmethod]
    pub fn demo_static(line: String) {}
}
5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.