attrs icon indicating copy to clipboard operation
attrs copied to clipboard

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

Open jerub opened this issue 3 years ago • 0 comments

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)

jerub avatar Jun 28 '22 14:06 jerub