Search code examples
pythonpython-2.7typessetsubclassing

Python: Subclassing frozenset not iterable?


Subclassing frozenset and set doesn't seem to work the same when it comes to iterables. Try to run the following MWE:

class MonFrozenSet(frozenset):
    def __new__(self, data):
        super(MonFrozenSet,self).__init__(data)
        return self

class MonSet(set):
    def __init__(self, data):
        super(MonSet,self).__init__(data)



x=(1,2,3,4)

A=MonSet(x)
B=MonFrozenSet(x)

for y in A: #Works
    print y

for y in B: #Doesn't work
    print y

The second for returns:

for y in B:
TypeError: 'type' object is not iterable

Any idea on how I can solve this?

If you are asking yourselves why I would like to use frozenset, the anwer is that I am trying to create a set of sets of tuples. The sets of tuples will be frozenset and the set of sets of tuples will be a set.

I use Python-2.7


Solution

  • When overriding __new__ you need to call the superclass's __new__, not its __init__. Also, you need to pass self (better named cls), since __new__ is a classmethod. Also, you need to return the result, since __new__ actually creates an object, it doesn't modify self. So:

    class MonFrozenSet(frozenset):
        def __new__(cls, data):
            return super(MonFrozenSet,cls).__new__(cls, data)
    

    Then:

    >>> a = MonFrozenSet([1, 2, 3])
    >>> for item in a:
    ...     print item
    1
    2
    3