Skip to content

#[pyo3(from_py_with = "...")] causes compilation error when used in methods with the #[setter] attribute. #3992

Closed

Description

@MarquessV

Bug Description

Using the from_py_with per-argument option inside a method with the #[setter] attribute causes a compilation error despite working fine in constructors and other methods without the setter attribute. The following code reproduces the issue with the error:

the trait bound `Field: pyo3::PyClass` is not satisfied
     the trait `pyo3::PyClass` is implemented for `Foo`
     required for `Field` to implement `pyo3::FromPyObject<'_>` [E0277]
use pyo3::prelude::*;

#[derive(Clone)]
struct Field(pub i32);

fn from_py_to_field(value: &PyAny) -> PyResult<Field> {
    let value = value.extract()?;
    Ok(Field(value))
}

#[pyclass]
struct Foo {
    field: Field,
}

#[pymethods]
impl Foo {
    // These compile successfully.
    #[new]
    fn new(#[pyo3(from_py_with = "from_py_to_field")] field: Field) -> Self {
        Self { field }
    }

    fn set_field_fn(&mut self, #[pyo3(from_py_with = "from_py_to_field")] field: Field) {
        self.field = field;
    }

    // This does not compile: "the trait bound `Field: pyo3::PyClass` is not satisfied"
    #[setter]
    fn field(&mut self, #[pyo3(from_py_with = "from_py_to_field")] field: Field) {
        self.field = field
    }
}

I've tested this in 0.20.3 and 0.21.0-beta.0 with the new Bound smart pointer.

Steps to Reproduce

  1. Annotate the argument of a #[setter] method with #[pyo3(from_py_with="..")] for some argument that doesn't implement PyClass (or run the example from the issue).
  2. Compile

Backtrace

No response

Your operating system and version

MacOS Sonoma (M1 Max)

Your Python version (python --version)

N/A

Your Rust version (rustc --version)

rustc 1.76.0 (07dca489a 2024-02-04)

Your PyO3 version

0.20.3 and 0.21-beta.0

How did you install python? Did you use a virtualenv?

I install python with pyenv, but this issue does not require a Python installation or virtual environment to reproduce.

Additional Info

No response

Activity

  1. Icxolu commented on Mar 26, 2024

    @Icxolu
    Member

    It seems like the #[pyo3(from_py_with = "...")] attribute was not handled for #[setter] methods at all, so pyo3 tried to extract Field here using FromPyObject. Since Field does not implement FromPyObject that failed.

    I don't see a reason why #[pyo3(from_py_with = "...")] should not be supported here, so I implemented a fix in #3995

  2. added theissue type on Nov 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions