Derive Macro PyReflectedSub

Source
#[derive(PyReflectedSub)]
Expand description

Derive macro generating an impl of __rsub__ method by Sub trait.

§Expansion

This implements:

#[pymethods]
impl PyClass {
    fn __rsub__(&self, other: &Self) -> <&Self as Sub<&Self>>::Output {
        Sub::sub(other, self)
    }
}

§Example

use std::ops::Sub;

use pyo3::{prelude::*, py_run};

use pyderive::PyNew;
use pyderive::ops::PyReflectedSub;

#[derive(PyNew, PyReflectedSub)]
#[pyclass(get_all)]
struct PyClass {
    field: i64
}

impl Sub for &PyClass {
    type Output = PyClass;

    fn sub(self, rhs: Self) -> Self::Output {
        PyClass { field: self.field - rhs.field }
    }
}

let test = "
actual = PyClass(2) - PyClass(1)
assert actual.field == 1
";

Python::with_gil(|py| {
    let PyClass = py.get_type::<PyClass>();
    py_run!(py, PyClass, test)
});