docs: demonstrate `NotImplemented` in `__richcmp__`

This commit is contained in:
David Hewitt 2022-08-21 13:01:19 +01:00
parent f574168974
commit ef8ccc0deb
1 changed files with 31 additions and 7 deletions

View File

@ -174,6 +174,30 @@ impl Number {
It checks that the `std::cmp::Ordering` obtained from Rust's `Ord` matches
the given `CompareOp`.
Alternatively, if you want to leave some operations unimplemented, you can
return `py.NotImplemented()` for some of the operations:
```rust
use pyo3::class::basic::CompareOp;
# use pyo3::prelude::*;
#
# #[pyclass]
# struct Number(i32);
#
#[pymethods]
impl Number {
fn __richcmp__(&self, other: &Self, op: CompareOp, py: Python<'_>) -> PyObject {
match op {
CompareOp::Eq => (self.0 == other.0).into_py(py),
CompareOp::Ne => (self.0 != other.0).into_py(py),
_ => py.NotImplemented(),
}
}
}
```
### Truthyness
We'll consider `Number` to be `True` if it is nonzero: