python-attrs / python-attrs/attrs

Extending attrs-generated `__eq__`

Open
#1,452 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Description

Hi, I fear that there is probably a super obvious answer to this question, but I somehow cannot wrap my head around it: is there any way how I can "extend" the attrs-generated __eq__ method, similar to how it's possible for __init__ by calling __attrs_init__? 🤔

Here just a dummy example to illustrate the situation. Right now, the only way I can get it work is by writing the boilerplate myself.

from attrs import define

magic_object = object()
"""Is equal to all objects."""


@define
class X:
    here: int
    are: float
    many: str
    fields: bool

    def __eq__(self, other):
        if other is magic_object:
            return True
        
        # Ideally, I want to call something like:
        # return __attrs_eq__(other)

        # Instead, I have this boilerplate code!
        return (
            super().__eq__(other)
            and isinstance(other, X)
            and self.here == other.here
            and self.are == other.are
            and self.many == other.many
            and self.fields == other.fields
        )


assert X(0, 0.0, "a", True) == X(0, 0.0, "a", True)
assert X(0, 0.0, "a", True) != X(0, 0.0, "a", False)
assert X(0, 0.0, "a", True) == magic_object

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at attrs' generated eq entry point and compare it with the attrs_init extension path shown in the issue. Use the provided X and magic_object example to define the expected behavior, including preserving generated field comparisons while allowing custom equality logic.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
developer-experience
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.