Randomuser123
Randomuser123

Reputation: 61

Hashing within a class

Im trying to hash an object of a custom class using the

hash()

function. My code does the following within the class

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

Where the attribute somelistattribute is list of lists such as:

Why do i keep getting an error:

TypeError: unhashable type: 'list'

How do I fix it?

Upvotes: 0

Views: 168

Answers (2)

Dan Getz
Dan Getz

Reputation: 9152

The problem is the lists inside of your outer list. Those aren't hashable, and calling tuple() only changes the outer list to a tuple.

You can fix this in a few ways, like with map():

hash(tuple(map(tuple, list_of_lists)))

or with a comprehension:

hash(tuple(tuple(x) for x in list_of_lists))

Upvotes: 0

zondo
zondo

Reputation: 20366

Because list is unhashable, and that includes the sublists. To convert the sublists, use map():

    return hash(tuple(map(tuple, self.somelistattribute)))

Upvotes: 3

Related Questions