Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

frozenset() - Example of when one might use them

Could I be supplied with some simple examples of when using a frozenset would be the best option to help me understand the concept more please.

like image 764
Phoenix Avatar asked Mar 12 '14 17:03

Phoenix


People also ask

What is Frozenset ()? Give an example?

Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. Due to this, frozen sets can be used as keys in Dictionary or as elements of another set.

What is the use of Frozenset?

Definition and Usage The frozenset() function returns an unchangeable frozenset object (which is like a set object, only unchangeable).

What is difference between set and Frozenset?

Frozenset is similar to set in Python, except that frozensets are immutable, which implies that once generated, elements from the frozenset cannot be added or removed. This function accepts any iterable object as input and transforms it into an immutable object.

What is the difference between tuple and Frozenset?

tuples are immutable lists , frozensets are immutable sets . frozensets aren't indexed, but you have the functionality of sets - O(1) element lookups, and functionality such as unions and intersections. They also can't contain duplicates, like their mutable counterparts.


2 Answers

frozenset() objects can be used as dictionary keys and as values inside of set() and frozenset() objects, where set objects cannot. set() values are mutable and not hashable, frozenset() values are immutable and are hashable.

They are to set objects what tuple objects are to list objects.

Demo:

>>> s = set([1, 2])
>>> fs = frozenset(s)
>>> adict = {}
>>> adict[s] = 42   # a set as key does not work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> adict[fs] = 42  # a frozenset as key works
>>> s.add(s)        # a set as value in a set does not work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> s.add(fs)       # a frozenset as value in a set works

Recent Python versions will optimize the use of a set literal:

if somevar in {'foo', 'bar', 'baz'}:

by storing a frozenset() constant with the bytecode:

>>> import dis
>>> dis.dis(compile("if somevar in {'foo', 'bar', 'baz'}: pass", '<stdin>', 'exec'))
  1           0 LOAD_NAME                0 (somevar) 
              3 LOAD_CONST               4 (frozenset({'foo', 'baz', 'bar'})) 
              6 COMPARE_OP               6 (in) 
              9 POP_JUMP_IF_FALSE       15 
             12 JUMP_FORWARD             0 (to 15) 
        >>   15 LOAD_CONST               3 (None) 
             18 RETURN_VALUE         

because the set literal cannot be mutated anyway; this makes using sets to test against very efficient. A regular set() cannot be stored this way as that would allow you to mutate the constant stored with the byte object.

like image 96
Martijn Pieters Avatar answered Oct 18 '22 13:10

Martijn Pieters


To compliment what Martijn said, I frequently use them for cache keys. For example, a memoize decorator that would key off (args, frozenset(kwargs.items()).

like image 41
Ben Avatar answered Oct 18 '22 15:10

Ben