Skip to content
Advertisement

Custom class to represent sets of length 1 [closed]

I would like to write my own class Singleton that represents a set of size 1. It should

  1. subclass frozenset so that all the usual set operations work seamlessly between Singleton, set, frozenset, and
  2. add an assertion to __init__ of frozenset that checks that the underlying set is constructed on an iterable of length 1.

What is a clean way to do this? Subclassing? Decorators? Thank you for your advice.

Advertisement

Answer

I’d just subclass frozenset and assert its length is 1.

class Singleton(frozenset):
    def __new__(cls, data):
        obj = super(Singleton, cls).__new__(cls, data)
        assert len(obj) == 1, "Must be of length 1"
        return obj

But that is literally a just going to be a frozenset of length 1.

x = Singleton([1])
print(x)
# Singleton({1})

print(Singleton([1]) | {2, 3})
# frozenset({1, 2, 3})

print(Singleton([1]) | Singleton([2]))
# frozenset({1, 2})

y = Singleton([1, 2])
# AssertionError: Must be of length 1

Not sure how useful the object would be, as most operations with Singleton operands are not going to be Singleton.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement