Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Python "Everything" keyword that always returns True for membership tests

Tags:

python

I feel like I want an "Everything" keyword in Python that would have the following properties:

  • Any boolean test of the form x in Everything would always return True, regardless of x.
  • Any attempt to iterate it, such as for x in Everything would raise an exception

My motivation is that I would like to have an optional whitelist and test something for membership in it, however I would like the default to simply pass.

So rather than writing:

def check_allowed(x, whitelist=None):
    if whitelist is None or x in whitelist:
        print("x is ok")
    else:
        print("x is not ok")

I'd like to do:

def check_allowed(x, whitelist=Everything):
    if x in whitelist:
        print("x is ok")
    else:
        print("x is not ok")

To me, the second version seems simpler and more Pythonic, however I don't know how one would implement such a thing.

Alternatively, I will accept explanations for why the first version is better and this is something I shouldn't desire.

like image 752
Scott Ritchie Avatar asked Jan 14 '14 09:01

Scott Ritchie


1 Answers

class Everything(object):
    def __contains__(self, other):
        return True

everything = Everything()

print 212134 in everything
print everything in everything
print None in everything
for i in everything:
    print i # TypeError.

This class implements the__contains__ behaviour for the in keyword. Thankfully ducktyping allows for us to look like a container and not be iterable.

To read more about __contains__ click here

To be used as such

everything_ever = Everything()
def check_allowed(x, whitelist=everything_ever):
    if x in whitelist:
        print("x is ok")
    else:
        print("x is not ok")
like image 173
Jakob Bowyer Avatar answered Nov 09 '22 04:11

Jakob Bowyer