What is the return value when implementing __contains__?


#1

Question

When implementing __contains__() for a class, what is the proper return value to use?

Answer

The __contains__() method should always either return the values True or False to indicate whether the object “contains” the item being checked. How the class implements that check is dependent on the data contained in the class. However, the method should always return either True or False. If the method returns any other value, Python will try to convert or interpret the value as True or False and the resulting behavior may be unexpected.