Generate object comparison method. Excellent for ``__eq__``, ``__le__``, etc. Examples: The example: .. sourcecode:: python CompareMethod( name='__eq__', op='==', fields=['x', 'y'], ) Generat
(
name: str, op: str, fields: List[str], **kwargs: Any
)
| 191 | |
| 192 | |
| 193 | def CompareMethod( |
| 194 | name: str, op: str, fields: List[str], **kwargs: Any |
| 195 | ) -> Callable[[], None]: |
| 196 | """Generate object comparison method. |
| 197 | |
| 198 | Excellent for ``__eq__``, ``__le__``, etc. |
| 199 | |
| 200 | Examples: |
| 201 | The example: |
| 202 | |
| 203 | .. sourcecode:: python |
| 204 | |
| 205 | CompareMethod( |
| 206 | name='__eq__', |
| 207 | op='==', |
| 208 | fields=['x', 'y'], |
| 209 | ) |
| 210 | |
| 211 | Generates a method like this: |
| 212 | |
| 213 | .. sourcecode:: python |
| 214 | |
| 215 | def __eq__(self, other): |
| 216 | if other.__class__ is self.__class__: |
| 217 | return (self.x,self.y) == (other.x,other.y) |
| 218 | return NotImplemented |
| 219 | """ |
| 220 | self_tuple = obj_attrs_tuple("self", fields) |
| 221 | other_tuple = obj_attrs_tuple("other", fields) |
| 222 | return Method( |
| 223 | name, |
| 224 | ["other"], |
| 225 | [ |
| 226 | "if other.__class__ is self.__class__:", |
| 227 | f" return {self_tuple}{op}{other_tuple}", |
| 228 | "return NotImplemented", |
| 229 | ], |
| 230 | **kwargs, |
| 231 | ) |
| 232 | |
| 233 | |
| 234 | def obj_attrs_tuple(obj_name: str, attrs: List[str]) -> str: |