pyo3_pytests/
comparisons.rs

1use pyo3::prelude::*;
2
3#[pyclass]
4struct Eq(i64);
5
6#[pymethods]
7impl Eq {
8    #[new]
9    fn new(value: i64) -> Self {
10        Self(value)
11    }
12
13    fn __eq__(&self, other: &Self) -> bool {
14        self.0 == other.0
15    }
16
17    fn __ne__(&self, other: &Self) -> bool {
18        self.0 != other.0
19    }
20}
21
22#[pyclass]
23struct EqDefaultNe(i64);
24
25#[pymethods]
26impl EqDefaultNe {
27    #[new]
28    fn new(value: i64) -> Self {
29        Self(value)
30    }
31
32    fn __eq__(&self, other: &Self) -> bool {
33        self.0 == other.0
34    }
35}
36
37#[pyclass(eq)]
38#[derive(PartialEq, Eq)]
39struct EqDerived(i64);
40
41#[pymethods]
42impl EqDerived {
43    #[new]
44    fn new(value: i64) -> Self {
45        Self(value)
46    }
47}
48
49#[pyclass]
50struct Ordered(i64);
51
52#[pymethods]
53impl Ordered {
54    #[new]
55    fn new(value: i64) -> Self {
56        Self(value)
57    }
58
59    fn __lt__(&self, other: &Self) -> bool {
60        self.0 < other.0
61    }
62
63    fn __le__(&self, other: &Self) -> bool {
64        self.0 <= other.0
65    }
66
67    fn __eq__(&self, other: &Self) -> bool {
68        self.0 == other.0
69    }
70
71    fn __ne__(&self, other: &Self) -> bool {
72        self.0 != other.0
73    }
74
75    fn __gt__(&self, other: &Self) -> bool {
76        self.0 > other.0
77    }
78
79    fn __ge__(&self, other: &Self) -> bool {
80        self.0 >= other.0
81    }
82}
83
84#[pyclass]
85struct OrderedDefaultNe(i64);
86
87#[pymethods]
88impl OrderedDefaultNe {
89    #[new]
90    fn new(value: i64) -> Self {
91        Self(value)
92    }
93
94    fn __lt__(&self, other: &Self) -> bool {
95        self.0 < other.0
96    }
97
98    fn __le__(&self, other: &Self) -> bool {
99        self.0 <= other.0
100    }
101
102    fn __eq__(&self, other: &Self) -> bool {
103        self.0 == other.0
104    }
105
106    fn __gt__(&self, other: &Self) -> bool {
107        self.0 > other.0
108    }
109
110    fn __ge__(&self, other: &Self) -> bool {
111        self.0 >= other.0
112    }
113}
114
115#[pymodule(gil_used = false)]
116pub fn comparisons(m: &Bound<'_, PyModule>) -> PyResult<()> {
117    m.add_class::<Eq>()?;
118    m.add_class::<EqDefaultNe>()?;
119    m.add_class::<EqDerived>()?;
120    m.add_class::<Ordered>()?;
121    m.add_class::<OrderedDefaultNe>()?;
122    Ok(())
123}
⚠️ Internal Docs ⚠️ Not Public API 👉 Official Docs Here