I would like to write my own class Singleton
that represents a set of size 1. It should
- subclass
frozenset
so that all the usual set operations work seamlessly betweenSingleton
,set
,frozenset
, and - add an assertion to
__init__
offrozenset
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.
JavaScript
x
6
1
class Singleton(frozenset):
2
def __new__(cls, data):
3
obj = super(Singleton, cls).__new__(cls, data)
4
assert len(obj) == 1, "Must be of length 1"
5
return obj
6
But that is literally a just going to be a frozenset
of length 1.
JavaScript
1
13
13
1
x = Singleton([1])
2
print(x)
3
# Singleton({1})
4
5
print(Singleton([1]) | {2, 3})
6
# frozenset({1, 2, 3})
7
8
print(Singleton([1]) | Singleton([2]))
9
# frozenset({1, 2})
10
11
y = Singleton([1, 2])
12
# AssertionError: Must be of length 1
13
Not sure how useful the object would be, as most operations with Singleton
operands are not going to be Singleton
.