frozenset() in Python

125 Views Asked by At

What is the meaning of the following function call?

InferTreeExp(frozenset(), inputList)

Here, the function frozenset() is passed without any parameters, inputList is an iterable (list) and InferTreeExp() is a user-defined function.

What's expected by calling frozenset() without a parameter passed?

As I can understand, frozenset(iterparam) creates an immutable set object from an iterable list passed as the parameter. Since here, there is no parameter passed, I do not understand the purpose or the result of calling the function.

1

There are 1 best solutions below

0
ti7 On

frozenset is just that, an immutable (frozen) set; calling it without any parameters or passing it an empty terable will create an empty instance of it, which is an iterable itself

>>> frozenset()     # nothing
frozenset()
>>> frozenset([])   # empty list
frozenset()
>>> frozenset(a for a in (None,) if a)  # generator which has no entries
frozenset()
>>> frozenset(range(0))  # empty Sequence
frozenset()
>>> frozenset(range(3))  # non-empty Sequence (NOTE order is not guaranteed)
frozenset({0, 1, 2})

This might be useful, for example, if the function checks for this specific case, simply to have an empty iterable which won't be mutated, or when the function defines some set logic

def foo(a, b):  # expects iterables
    for c in a:
        if a in b:
            ...
def foo(a, b):  # does some set logic
    c = a ^ b   # some other methods do coerce list to set
    ...
def foo(a, b):  # just directly checks if isinstance()
    if isinstance(a, frozenset):
       ...