Search code examples
pythonlistpython-3.ximmutabilityhashable

Making a list subclass hashable


I want to derive a class from list, add a few instance attributes to it, and make it hashable. What is a good (fast and neat) way to do it?

UPDATE:

I deleted a lengthy explanation of a use case. I also moved a related but separate issue into a different question.


Solution

  • This code is fine. You're making a copy of the list, which could be a bit slow.

    def __hash__(self):
        return hash(tuple(self.list_attribute))
    

    You have several options if you want to be faster.

    • Store list_attribute as a tuple, not a list (after it is fully constructed)
    • Compute the hash once at init time and store the hash value. You can do this because your class is immutable, so the hash will never change.
    • Write your own hash function. Here's the hash function for tuple, do something similar.