| 1 |
# Comparison |
| 2 |
|
| 3 |
By default, two instances of *attrs* classes are equal if they have the same type and all their fields are equal. |
| 4 |
For that, *attrs* writes `__eq__` and `__ne__` methods for you. |
| 5 |
|
| 6 |
Additionally, if you pass `order=True`, *attrs* will also create a complete set of ordering methods: `__le__`, `__lt__`, `__ge__`, and `__gt__`. |
| 7 |
|
| 8 |
Both for equality and order, *attrs* will: |
| 9 |
|
| 10 |
- Check if the types of the instances you're comparing are equal, |
| 11 |
- if so, create a tuple of all field values for each instance, |
| 12 |
- and finally perform the desired comparison operation on those tuples. |
| 13 |
|
| 14 |
[^default]: That's the default if you use the {func}`attr.s` decorator, but not with {func}`~attrs.define`. |
| 15 |
|
| 16 |
(custom-comparison)= |
| 17 |
|
| 18 |
## Customization |
| 19 |
|
| 20 |
As with other features, you can exclude fields from being involved in comparison operations: |
| 21 |
|
| 22 |
```{doctest} |
| 23 |
>>> from attrs import define, field |
| 24 |
>>> @define |
| 25 |
... class C: |
| 26 |
... x: int |
| 27 |
... y: int = field(eq=False) |
| 28 |
|
| 29 |
>>> C(1, 2) == C(1, 3) |
| 30 |
True |
| 31 |
``` |
| 32 |
|
| 33 |
Additionally you can also pass a *callable* instead of a bool to both *eq* and *order*. |
| 34 |
It is then used as a key function like you may know from {func}`sorted`: |
| 35 |
|
| 36 |
```{doctest} |
| 37 |
>>> @define |
| 38 |
... class S: |
| 39 |
... x: str = field(eq=str.lower) |
| 40 |
|
| 41 |
>>> S("foo") == S("FOO") |
| 42 |
True |
| 43 |
|
| 44 |
>>> @define(order=True) |
| 45 |
... class C: |
| 46 |
... x: str = field(order=int) |
| 47 |
|
| 48 |
>>> C("10") > C("2") |
| 49 |
True |
| 50 |
``` |
| 51 |
|
| 52 |
This is especially useful when you have fields with objects that have atypical comparison properties. |
| 53 |
Common examples of such objects are [NumPy arrays](https://github.com/python-attrs/attrs/issues/435). |
| 54 |
|
| 55 |
To save you unnecessary boilerplate, *attrs* comes with the {func}`attrs.cmp_using` helper to create such functions. |
| 56 |
For NumPy arrays it would look like this: |
| 57 |
|
| 58 |
```python |
| 59 |
import numpy |
| 60 |
|
| 61 |
@define |
| 62 |
class C: |
| 63 |
an_array = field(eq=attrs.cmp_using(eq=numpy.array_equal)) |
| 64 |
``` |
| 65 |
|
| 66 |
:::{warning} |
| 67 |
Please note that *eq* and *order* are set *independently*, because *order* is `False` by default in {func}`~attrs.define` (but not in {func}`attr.s`). |
| 68 |
You can set both at once by using the *cmp* argument that we've undeprecated just for this use-case. |
| 69 |
::: |