I feel like I want an "Everything" keyword in Python that would have the following properties:
x in Everything
would always return True, regardless of x.for x in Everything
would raise an exceptionMy 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.
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")
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