diff --git a/changelog.d/787.change.rst b/changelog.d/787.change.rst index c5d534a6..767a5825 100644 --- a/changelog.d/787.change.rst +++ b/changelog.d/787.change.rst @@ -1 +1,3 @@ -To make it easier to customize attribute comparison (#435), add the ``attr.cmp_with()`` helper. +To make it easier to customize attribute comparison (#435), we have added the ``attr.cmp_with()`` helper. + +See the `new docs on comparison `_ for more details. diff --git a/docs/api.rst b/docs/api.rst index 0a370048..3df31450 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -173,6 +173,8 @@ Helpers ``attrs`` comes with a bunch of helper methods that make working with it easier: +.. autofunction:: attr.cmp_using + .. autofunction:: attr.fields For example: diff --git a/docs/comparison.rst b/docs/comparison.rst index 307796fb..d3c2f625 100644 --- a/docs/comparison.rst +++ b/docs/comparison.rst @@ -42,5 +42,17 @@ It is then used as a key function like you may know from `sorted`: This is especially useful when you have fields with objects that have atypical comparison properties. Common examples of such objects are `NumPy arrays `_. -Please note that *eq* and *order* are set *independently*, because *order* is `False` by default in `modern APIs `. -You can set both at once by using the *cmp* argument that we've undeprecated just for this use-case. +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:: + + import numpy as np + + @attr.s(order=False) + class C: + an_array = attr.ib(eq=attr.cmp_using(eq=np.array_equal)) + + +.. warning:: + + Please note that *eq* and *order* are set *independently*, because *order* is `False` by default in `modern APIs `. + You can set both at once by using the *cmp* argument that we've undeprecated just for this use-case. diff --git a/src/attr/_cmp.py b/src/attr/_cmp.py index 89670bb4..b747b603 100644 --- a/src/attr/_cmp.py +++ b/src/attr/_cmp.py @@ -19,8 +19,8 @@ def cmp_using( class_name="Comparable", ): """ - Utility function that creates a class with customized equality and - ordering methods. + Create a class that can be passed into `attr.ib`'s ``eq``, ``order``, and + ``cmp`` arguments to customize field comparison. The resulting class will have a full set of ordering methods if at least one of ``{lt, le, gt, ge}`` and ``eq`` are provided. @@ -41,6 +41,8 @@ def cmp_using( :param Optional[str] class_name: Name of class. Defaults to 'Comparable'. + See `comparison` for more details. + .. versionadded:: 21.1.0 """