Skip to content

Extending attrs-generated __eq__ #1452

@AdrianSosic

Description

@AdrianSosic

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions