Struct pyo3::pyclass_init::PyClassInitializer[][src]

pub struct PyClassInitializer<T: PyClass> { /* fields omitted */ }
Expand description

Initializer for our #[pyclass] system.

You can use this type to initalize complicatedly nested #[pyclass].

Examples

#[pyclass(subclass)]
struct BaseClass {
    #[pyo3(get)]
    basename: &'static str,
}
#[pyclass(extends=BaseClass, subclass)]
struct SubClass {
    #[pyo3(get)]
    subname: &'static str,
}
#[pyclass(extends=SubClass)]
struct SubSubClass {
    #[pyo3(get)]
    subsubname: &'static str,
}

#[pymethods]
impl SubSubClass {
    #[new]
    fn new() -> PyClassInitializer<Self> {
        PyClassInitializer::from(BaseClass { basename: "base" })
            .add_subclass(SubClass { subname: "sub" })
            .add_subclass(SubSubClass { subsubname: "subsub" })
    }
}
Python::with_gil(|py| {
    let typeobj = py.get_type::<SubSubClass>();
    let sub_sub_class = typeobj.call((), None).unwrap();
    py_run!(
        py,
        sub_sub_class,
        r#"
 assert sub_sub_class.basename == 'base'
 assert sub_sub_class.subname == 'sub'
 assert sub_sub_class.subsubname == 'subsub'"#
    );
});

Implementations

Construct new initializer from value T and base class’ initializer.

We recommend to mainly use add_subclass, instead of directly call new.

Constructs a new initializer from base class’ initializer.

Examples

#[pyclass]
struct BaseClass {
    value: u32,
}

impl BaseClass {
    fn new(value: i32) -> PyResult<Self> {
        Ok(Self {
            value: std::convert::TryFrom::try_from(value)?,
        })
    }
}
#[pyclass(extends=BaseClass)]
struct SubClass {}

#[pymethods]
impl SubClass {
    #[new]
    fn new(value: i32) -> PyResult<PyClassInitializer<Self>> {
        let base_init = PyClassInitializer::from(BaseClass::new(value)?);
        Ok(base_init.add_subclass(SubClass {}))
    }
}

Trait Implementations

Performs the conversion.

Performs the conversion.

Safety Read more

This trait is private to implement; this method exists to make it impossible to implement outside the crate. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.