Add example of dynamic return type in the "Python classes" section of the guide.

This commit is contained in:
Samuel Pastva 2023-10-26 16:36:55 -05:00
parent aa6622bb1a
commit 48c90d9586
1 changed files with 18 additions and 1 deletions

View File

@ -337,10 +337,27 @@ impl SubSubClass {
let super_ = self_.into_super(); // Get PyRef<'_, SubClass>
SubClass::method2(super_).map(|x| x * v)
}
#[staticmethod]
fn dynamic_type(py: Python<'_>, val: usize) -> PyResult<PyObject> {
let base = PyClassInitializer::from(BaseClass::new());
let sub = base.add_subclass(SubClass { val2: val });
if val % 2 == 0 {
Ok(Py::new(py, sub)?.to_object(py))
} else {
let sub_sub = sub.add_subclass(SubSubClass { val3: val });
Ok(Py::new(py, sub_sub)?.to_object(py))
}
}
}
# Python::with_gil(|py| {
# let subsub = pyo3::PyCell::new(py, SubSubClass::new()).unwrap();
# pyo3::py_run!(py, subsub, "assert subsub.method3() == 3000")
# pyo3::py_run!(py, subsub, "assert subsub.method3() == 3000");
# let subsub = SubSubClass::dynamic_type(py, 2).unwrap();
# let subsubsub = SubSubClass::dynamic_type(py, 3).unwrap();
# let cls = py.get_type::<SubSubClass>();
# pyo3::py_run!(py, subsub cls, "assert not isinstance(subsub, cls)");
# pyo3::py_run!(py, subsubsub cls, "assert isinstance(subsubsub, cls)");
# });
```