Immutable or frozen sets

Python 2.4 has a built-in data type called frozenset. It's similar to set, but it's immutable (that is, after you've created one, you can't change it). Because a frozenset is immutable, it can be used as a dict key or as an element in a set.

In the following example, a frozenset instance is used to associate a three-item set key with the value None:

>>> mylist = ['foo', 'bar', 'spam'] >>> s = frozenset(mylist) >>> s frozenset(['foo', 'bar', 'spam']) >>> d = {s: None} >>> d

If you try to use a regular set as a dict key, Python builds an immutable set from your set and uses that set as the dict key instead.

TECHNICAL Python 2.3 has a similar subclass of sets called immutableSet. It is STUFF available if you import the sets module.

Was this article helpful?

0 0

Post a comment