0

I have the following Python class:

class Test:
    def __init__(self, ints: List[int]) -> None:
        self.ints = ints
    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Test):
            return NotImplemented
        return self.ints == other.ints

Because I've overridden the equals method, I should implement the hash method. However, lists are not hashable in Python.

I've read that I can convert the List to a Tuple and hash that, but this feels a bit hacky. Are there any better options?

jd96
  • 535
  • 3
  • 12
  • Does this answer your question? [Hash function on list](https://stackoverflow.com/questions/23351415/hash-function-on-list) – Isma Jun 27 '21 at 06:24
  • 2
    If you feel that it's hacky, then how do you expect the hashing to work correctly when you change the inner list? Mutability is the reason `list` is not hashable, `tuple` is immutable and thus is OK to hash – Alexey S. Larionov Jun 27 '21 at 06:24
  • 3
    "Because I've overridden the equals method, I should implement the hash method" why do you say that? That isn't a valid inference. A relevant example: `list` objects implement `__eq__` but they do not implement `__hash__`... – juanpa.arrivillaga Jun 27 '21 at 06:57
  • @juanpa.arrivillaga ah interesting. I usually program in Java, where hash and equals methods need to be implemented together. But I suppose Python's restriction on what can be hashed removes that requirement. Thanks! – jd96 Jun 27 '21 at 10:54

0 Answers0