Using magic method __contains__

Using magic method __contains__#

Python is a high level language and allows you to do a lot of things with ease. One of the things that Python allows you to do is to check if an item is present in a list or tuple for example. This is done using the in operator as shown below.

Using the in operator to check if an item is present in a list#
if __name__ == '__main__':
    items = ['a', 'b', 'c']
    print('a' in items)  # True
    print('d' in items)  # False

This is a very simple and easy way to check if an item is present in a list or tuple. But what if you want to check if an item is present in a custom class? For this Python has a magic method called __contains__ which is used to check if an item is present in a container. This method is called when using the in operator.

In the example below, we have a class called Items which has a list of items. We have implemented the __contains__ method to check if an item is present in the list of items.

Using the __contains__ magic method to check if an item is present in a custom class#
class Items:
    def __init__(self, items):
        self.items = items

    def __contains__(self, item):
        return item in self.items


if __name__ == '__main__':
    items = Items(['a', 'b', 'c'])
    print('a' in items)  # True
    print('d' in items)  # False

This is a very simple and easy way to check if an item is present in a custom class. You can also use the __contains__ method to implement custom logic to check if an item is present in a class. It also allows you to present a more readable and understandable code to check if an item is present in a class.