The nutrition word "Everything", which always returns True for membership tests

It seems to me that I want the keyword "Everything" in Python, which will have the following properties:

  • Any logical test of the form x in Everything will always return True, regardless of x.
  • Any attempt to iterate, for example for x in Everything , will lead to the emergence of exclusion

My motivation is that I would like to have an extra whitelist and test something for its membership, but I would like it to be simply passed by default.

Therefore, instead of 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 would like to:

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

For me, the second version seems simpler and more Pythonic, however I do not know how to implement such a thing.

As an alternative, I will accept explanations why the first version is better, and this is what I should not wish for.

+6
source share
1 answer
 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__ behavior for the in keyword. Fortunately, ducktyping allows us to look like a container, rather than being iterable.

For more on __contains__ click here

For use 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") 
+17
source

All Articles