Skip to content

Suggestion: When eq=Callable, make __hash__ use the return value of the callable. #975

Open
@jerub

Description

@jerub

The specific situation is more complicated, but this is the minimal representation. I have a situation where I have a datastructure that is "frozen" and my contract with myself is I promise not to edit any of the values in it. But I can't use the attrs datastructure as a dict key because a field is mutable and unhashable.

def key_func(field: dict[str, str]):
  return sorted(field.keys())

@attrs.frozen
class Example:
  other: int
  field: dict[str, str]: attrs.field(eq=key_func)

I've "solved" this by adding the hash method:

  def __hash__(self):
    return hash((self.other, key_func(self.field)))

But it would be nice if we could do this natively via the API.

If necessary, either of these incantations seem sensible: attrs.field(eq=key_func, hash=True) or attrs.field(eq=key_func, hash=key_func)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions