In order to simplify my code, I would like to implement a set that contains everything, i.e. a UniversalSet
. I figure that the simplest of way of getting around this is to have a custom set that returns True for any query. In my particular case I am mostly interested in the __intersect__
of sets such that the following criteria are true:
u_set = UniversalSet()
u_set & {1, 2, 3} == {1, 2, 3} # (1)
{1, 2, 3} & u_set == {1, 2, 3} # (2)
I have subclassed set
in the following manner:
class UniversalSet(set):
def __and__(self, other):
return other
This works for (1)
, but (2)
still fails. Is there a similarly easy way to make (2)
to work?
You also need to define the reversed version of the and operator (__rand__
) so your subclasses methods get called when it is the second argument as well as the first.
class UniversalSet(set):
def __and__(self, other):
return other
def __rand__(self, other):
return other
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With