From 13cd092c4e87171462f422de804f25dd630ea436 Mon Sep 17 00:00:00 2001 From: Aviram Hassan <41201924+aviramha@users.noreply.github.com> Date: Wed, 23 Jun 2021 12:40:01 +0300 Subject: [PATCH] Update class.md - add example of `new` returning a `PyResult` (#1688) * Update class.md - add example of `new` returning a `PyResult` * Update class.md --- guide/src/class.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/guide/src/class.md b/guide/src/class.md index c0bc650a..3b5d3509 100644 --- a/guide/src/class.md +++ b/guide/src/class.md @@ -169,6 +169,23 @@ impl MyClass { } ``` +Alternatively, if your `new` method may fail you can return `PyResult`. +```rust +# use pyo3::prelude::*; +#[pyclass] +struct MyClass { + num: i32, +} + +#[pymethods] +impl MyClass { + #[new] + fn new(num: i32) -> PyResult { + Ok(MyClass { num }) + } +} +``` + If no method marked with `#[new]` is declared, object instances can only be created from Rust, but not from Python.