From f084ceb9b1441802facdc1143cd46e106e26c17e Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Sun, 6 Mar 2022 10:54:54 +0100 Subject: [PATCH] guide: fix duplicated example for #[new] The second one was probably intended to show a fallible `#[new]`. Also show that the method does not need to be named `new()`, which is nice because `new()` can be used for a Rust-level constructor if they differ. --- guide/src/class.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/guide/src/class.md b/guide/src/class.md index 81a25862..e40e4a5f 100644 --- a/guide/src/class.md +++ b/guide/src/class.md @@ -78,18 +78,26 @@ Alternatively, if your `new` method may fail you can return `PyResult`. ```rust # use pyo3::prelude::*; +# use pyo3::exceptions::PyValueError; # #[pyclass] -# struct Number(i32); +# struct Nonzero(i32); # #[pymethods] -impl Number { +impl Nonzero { #[new] - fn new(value: i32) -> Self { - Number(value) + fn py_new(value: i32) -> PyResult { + if value == 0 { + Err(PyValueError::new_err("cannot be zero")) + } else { + Ok(Nonzero(value)) + } } } ``` +As you can see, the Rust method name is not important here; this way you can +still use `new()` for a Rust-level constructor. + If no method marked with `#[new]` is declared, object instances can only be created from Rust, but not from Python.