Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

def__hash__(self):
    returnhash(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.

Solution 2:

You can apply tuple to self:

classState(list):
    def__hash__(self):
        returnhash((self.some_attribute, tuple(self)))

tuple-ing self takes about half the time of the whole hashing process:

from timeit import timeit

setup = "from __main__ import State; s = State(range(1000)); s.some_attribute = 'foo'"
stmt = "hash(s)"
print(timeit(stmt=stmt, setup=setup, number=100000))

setup = "r = list(range(1000))"
stmt = "tuple(r)"
print(timeit(stmt=stmt, setup=setup, number=100000))

prints

0.9382011891054844
0.3911763069244216

Solution 3:

This is more of a comment than an answer, but it's too long to be a comment. This is how one can accesses instance attributes from inside __new__:

classData(tuple):
    def__new__(klass, arg):
        data_inst = tuple.__new__(klass, arg)
        data_inst.min = min(data_inst)
        data_inst.max = max(data_inst)
        return data_inst

>>> d = Data([1,2,3,4])
>>> d
(1, 2, 3, 4)
>>> d.min1>>> d.max4>>> d1 = Data([1,2,3,4,5,6])
>>> d1.max6>>> d.max4

Post a Comment for "Making A List Subclass Hashable"