Question

I heard about the line "immutable objects are hashable", below like this,

Frozensets are immutable and always hashable.

But tuples are immutable but not hashable? Why?

Était-ce utile?

La solution

Tuples are very much hashable if the elements inside are hashable.

>>> hashable = (1,2,4)
>>> not_hashable = ([1,2],[3,4])
>>> hash_check = {}
>>> hash_check[hashable] = True
>>> hash_check
{(1, 2, 4): True}
>>> hash_check[not_hashable] = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> 

Autres conseils

Even though tuples are immutable themselves, they might contain mutable objects, for example, if we could do:

person = {'name': 'John', 'surname': 'Doe'}
key = (person, True)

cache = {}
cache[key] = datetime.now()  # for example

person['surname'] = 'Smith'

cache[key]  # What is the expected result?

Not all immutable objects are hashable. Furthermore, only tuples that contain mutable objects are not hashable.

>>> t = (1, 2)
>>> hash(t)
1299869600
>>> t = ([1], [2])  
>>> hash(t)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    hash(t)
TypeError: unhashable type: 'list'

So, the problem is the list, not the tuple.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top