Last week I did two rounds of my Creating Python modules in Rust workshop. During the second session on Sunday, someone asked if we can create standard dunder methods, say __str__
or __repr__
. I never did that before, and during the session I tried to read the docs and implement it. And I failed :)
Later I realized that I should have read the docs carefully. To add those methods, we will have to implement PyObjectProtocol for the Rust structure.
#[pyproto]
impl PyObjectProtocol for Ros {
fn __repr__(&self) -> PyResult<String> {
let cpus = self.sys.get_processors().len();
let repr = format!("<Ros(CPUS: {})>", cpus);
Ok(repr)
}
fn __str__(&self) -> PyResult<String> {
let cpus = self.sys.get_processors().len();
let repr = format!("<Ros(CPUS: {})>", cpus);
Ok(repr)
}
}
>>> from randomos import Ros
>>> r = Ros()
>>> r
<Ros (CPUS: 8)>
>>> str(r)
'<Ros (CPUS: 8)>'
This code example is in the ros-more branch of the code.
from Planet Python
via read more
No comments:
Post a Comment