2021-02-26 06:53:57 +00:00
Comparison
==========
By default, two instances of `` attrs `` classes are equal if all their fields are equal.
For that, `` attrs `` writes `` __eq__ `` and `` __ne__ `` methods for you.
Additionally, if you pass `` order=True `` (which is the default if you use the `attr.s` decorator), ``attrs`` will also create a full set of ordering methods that are based on the defined fields: ``__ le__`` , ` ` __lt__ `` , `` __ge__ `` , and `` __gt__ `` .
2021-10-06 10:21:36 +00:00
.. _custom-comparison:
2021-02-26 06:53:57 +00:00
Customization
-------------
As with other features, you can exclude fields from being involved in comparison operations:
.. doctest ::
2021-11-22 06:35:36 +00:00
>>> from attr import define, field
>>> @define
... class C:
... x: int
... y: int = field(eq=False)
2021-02-26 06:53:57 +00:00
>>> C(1, 2) == C(1, 3)
True
Additionally you can also pass a *callable* instead of a bool to both *eq* and *order* .
It is then used as a key function like you may know from `sorted` :
.. doctest ::
2021-11-22 06:35:36 +00:00
>>> from attr import define, field
>>> @define
... class S:
... x: str = field(eq=str.lower)
2021-02-26 06:53:57 +00:00
>>> S("foo") == S("FOO")
True
2021-11-22 06:35:36 +00:00
>>> @define(order=True)
... class C:
... x: str = field(order=int)
2021-02-26 06:53:57 +00:00
>>> C("10") > C("2")
True
This is especially useful when you have fields with objects that have atypical comparison properties.
Common examples of such objects are `NumPy arrays <https://github.com/python-attrs/attrs/issues/435> `_ .
2021-05-04 15:41:14 +00:00
To save you unnecessary boilerplate, `` attrs `` comes with the `attr.cmp_using` helper to create such functions.
For NumPy arrays it would look like this::
2021-05-05 08:15:26 +00:00
import numpy
2021-05-04 15:41:14 +00:00
2021-11-22 06:35:36 +00:00
@define(order=False)
2021-05-04 15:41:14 +00:00
class C:
2021-11-22 06:35:36 +00:00
an_array = field(eq=attr.cmp_using(eq=numpy.array_equal))
2021-05-04 15:41:14 +00:00
.. warning ::
2021-12-25 14:15:10 +00:00
Please note that *eq* and *order* are set *independently* , because *order* is `False` by default in `attrs.define` (but not in `attr.s` ).
2021-05-04 15:41:14 +00:00
You can set both at once by using the *cmp* argument that we've undeprecated just for this use-case.