Skip to content

Commit dc251d0

Browse files
authored
Merge pull request #3552 from daemontus/main
docs: Example of dynamic return type in the "Python classes" guide
2 parents 579af5e + 2fbc02d commit dc251d0

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

guide/src/class.md

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -337,10 +337,27 @@ impl SubSubClass {
337337
let super_ = self_.into_super(); // Get PyRef<'_, SubClass>
338338
SubClass::method2(super_).map(|x| x * v)
339339
}
340+
341+
#[staticmethod]
342+
fn factory_method(py: Python<'_>, val: usize) -> PyResult<PyObject> {
343+
let base = PyClassInitializer::from(BaseClass::new());
344+
let sub = base.add_subclass(SubClass { val2: val });
345+
if val % 2 == 0 {
346+
Ok(Py::new(py, sub)?.to_object(py))
347+
} else {
348+
let sub_sub = sub.add_subclass(SubSubClass { val3: val });
349+
Ok(Py::new(py, sub_sub)?.to_object(py))
350+
}
351+
}
340352
}
341353
# Python::with_gil(|py| {
342354
# let subsub = pyo3::PyCell::new(py, SubSubClass::new()).unwrap();
343-
# pyo3::py_run!(py, subsub, "assert subsub.method3() == 3000")
355+
# pyo3::py_run!(py, subsub, "assert subsub.method3() == 3000");
356+
# let subsub = SubSubClass::factory_method(py, 2).unwrap();
357+
# let subsubsub = SubSubClass::factory_method(py, 3).unwrap();
358+
# let cls = py.get_type::<SubSubClass>();
359+
# pyo3::py_run!(py, subsub cls, "assert not isinstance(subsub, cls)");
360+
# pyo3::py_run!(py, subsubsub cls, "assert isinstance(subsubsub, cls)");
344361
# });
345362
```
346363

0 commit comments

Comments
 (0)