Skip to content

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

Closed
@davidhewitt

Description

@davidhewitt

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(())
        })
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions