Skip to content

Add #[pyo3(default)] option for FromPyObject derives #4643

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
davidhewitt opened this issue Oct 24, 2024 · 4 comments
Closed

Add #[pyo3(default)] option for FromPyObject derives #4643

davidhewitt opened this issue Oct 24, 2024 · 4 comments

Comments

@davidhewitt
Copy link
Member

davidhewitt commented Oct 24, 2024

Continuing from #3605

The request is to add a #[pyo3(default)] attribute to allow missing values to be filled in, similar to serde. Note that serde allows Option<T> fields to be missing and fills them with None by default without requiring the attribute; in the linked discussion we agreed that was too implicit for us here.

    use pyo3::FromPyObject;
    #[derive(FromPyObject, Clone)]
    #[pyo3(from_item_all)]
    struct Test {
        pub a: String,
        #[pyo3(default)]    // <-- this would be the new attribute
        pub b: Option<String>,
    }

    #[test]
    fn test_option() -> Result<()> {
        Python::with_gil(|py| {
            let result: Test =
                py.eval("{'a': 'test'}", None, None).wrap_err("eval failed")?.extract()?;
            assert!(result.a == "test");
            assert!(result.b.is_none());
            Ok(())
        })
    }
@davidhewitt davidhewitt changed the title Add #[pyo3(default)] option for `FromPyObject derives Add #[pyo3(default)] option for FromPyObject derives Oct 24, 2024
@Icxolu
Copy link
Contributor

Icxolu commented Jan 10, 2025

Implemented in #4829

@Icxolu Icxolu closed this as completed Jan 10, 2025
@bbstilson
Copy link

bbstilson commented Feb 27, 2025

I saw the PR merged, and some releases have happened since, but it doesn't seem available in 0.23.5:

error: expected one of: `attribute`, `item`, `from_py_with`
   --> src/foo.rs:10:12
    |
137 |     #[pyo3(default)]
    |            ^^^^^^^

Is this behind a feature flag or is it planned for a later release? Or am I just holding it wrong 😖

@Icxolu
Copy link
Contributor

Icxolu commented Feb 27, 2025

This only landed after the initial 0.23 release. We usually do not backport new features, so this will be available from 0.24. We plan to release that soonish, see #4905.

@bbstilson
Copy link

Awesome! Thank you

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

No branches or pull requests

3 participants