Skip to content

Implement FromPyObject for all types frequently created from dictionaries or strings #33

@smartgoo

Description

@smartgoo

Consider adding custom FromPyObject impl for Python-exposed structs which are commonly created from Python dicts or strings.

https://pyo3.rs/v0.27.1/class.html#customizing-the-class

For example (note this code doesn't fully work, is just an example):

#[pyclass(name = "CovenantBinding", skip_from_py_object)]
pub struct PyCovenantBinding(CovenantBinding);

impl<'a, 'py> FromPyObject<'a, 'py> for PyCovenantBinding {
    type Error = PyErr;

    fn extract(ob: Borrowed<'_, 'py, PyAny>) -> PyResult<Self> {
        // Try native CovenantBinding instance first, then fall back to dict
        if let Ok(cb) = ob.cast::<Self>() {
            return Ok(cb.get().clone());
        }
        let dict = ob.cast::<PyDict>()?;
        Self::try_from(dict)
    }
}

This would also be beneficial for types that are frequently accepted in function signatures as a concrete type instance or string. PyNetworkId for example currently has as custom FromPyObject implementation. This allows functions that accept args of type PyNetworkId to receive an instance or a string.

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