It can't even print an user-readable representation of itself! We can fix that by defining the
__repr__ and __str__ methods inside a #[pymethods] block. We do this by accessing the value
contained inside Number.
#![allow(unused)]fnmain() {
use pyo3::prelude::*;
#[pyclass]structNumber(i32);
#[pymethods]impl Number {
// For `__repr__` we want to return a string that Python code could use to recreate// the `Number`, like `Number(5)` for example.fn__repr__(&self) -> String {
// We use the `format!` macro to create a string. Its first argument is a// format string, followed by any number of parameters which replace the// `{}`'s in the format string.//// 👇 Tuple field access in Rust uses a dotformat!("Number({})", self.0)
}
// `__str__` is generally used to create an "informal" representation, so we// just forward to `i32`'s `ToString` trait implementation to print a bare number.fn__str__(&self) -> String {
self.0.to_string()
}
}
}
Let's also implement hashing. We'll just hash the i32. For that we need a Hasher. The one
provided by std is DefaultHasher, which uses the SipHash algorithm.
#![allow(unused)]fnmain() {
use std::collections::hash_map::DefaultHasher;
// Required to call the `.hash` and `.finish` methods, which are defined on traits.use std::hash::{Hash, Hasher};
use pyo3::prelude::*;
#[pyclass]structNumber(i32);
#[pymethods]impl Number {
fn__hash__(&self) -> u64 {
letmut hasher = DefaultHasher::new();
self.0.hash(&mut hasher);
hasher.finish()
}
}
}
Note: When implementing __hash__ and comparisons, it is important that the following property holds:
k1 == k2 -> hash(k1) == hash(k2)
In other words, if two keys are equal, their hashes must also be equal. In addition you must take
care that your classes' hash doesn't change during its lifetime. In this tutorial we do that by not
letting Python code change our Number class. In other words, it is immutable.
By default, all #[pyclass] types have a default hash implementation from Python.
Types which should not be hashable can override this by setting __hash__ to None.
This is the same mechanism as for a pure-Python class. This is done like so:
Unlike in Python, PyO3 does not provide the magic comparison methods you might expect like __eq__,
__lt__ and so on. Instead you have to implement all six operations at once with __richcmp__.
This method will be called with a value of CompareOp depending on the operation.