Skip to content
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

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

Open
davidhewitt opened this issue Oct 24, 2024 · 0 comments
Open

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

davidhewitt opened this issue Oct 24, 2024 · 0 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
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

1 participant