Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the All / Universal set

Tags:

python

set

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?

like image 243
imolit Avatar asked Feb 17 '15 16:02

imolit


1 Answers

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
like image 150
Simon Gibbons Avatar answered Oct 28 '22 17:10

Simon Gibbons