Skip to content

Commit

Permalink
Merge pull request #2213 from PyO3/guide_new_fix
Browse files Browse the repository at this point in the history
guide: fix duplicated example for #[new]
  • Loading branch information
davidhewitt committed Mar 6, 2022
2 parents 754edea + f084ceb commit ecfc4a1
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions guide/src/class.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,18 +78,26 @@ Alternatively, if your `new` method may fail you can return `PyResult<Self>`.

```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<Self> {
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.

Expand Down

0 comments on commit ecfc4a1

Please sign in to comment.