Why aren't Python sets hashable?

Dan Burton picture Dan Burton · Jun 10, 2011 · Viewed 34.9k times · Source

I stumbled across a blog post detailing how to implement a powerset function in Python. So I went about trying my own way of doing it, and discovered that Python apparently cannot have a set of sets, since set is not hashable. This is irksome, since the definition of a powerset is that it is a set of sets, and I wanted to implement it using actual set operations.

>>> set([ set() ])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

Is there a good reason Python sets are not hashable?

Answer

Sven Marnach picture Sven Marnach · Jun 10, 2011

Generally, only immutable objects are hashable in Python. The immutable variant of set() -- frozenset() -- is hashable.