0
0
PythonHow-ToBeginner · 3 min read

How to Implement __contains__ in Python: Simple Guide

To implement __contains__ in Python, define this method inside your class to return True if an item is found and False otherwise. This method lets you customize how the in keyword works with your objects.
📐

Syntax

The __contains__ method is defined inside a class and takes two parameters: self (the instance) and item (the element to check). It should return True if item is in the object, otherwise False.

python
class MyClass:
    def __contains__(self, item):
        # return True if item is found, else False
        pass
💻

Example

This example shows a class that stores a list of fruits and implements __contains__ to check if a fruit is in the list using the in keyword.

python
class FruitBasket:
    def __init__(self, fruits):
        self.fruits = fruits

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

basket = FruitBasket(['apple', 'banana', 'cherry'])

print('banana' in basket)  # True
print('orange' in basket)  # False
Output
True False
⚠️

Common Pitfalls

One common mistake is forgetting to return a boolean value (True or False) from __contains__. Another is not handling the item parameter properly, which can cause unexpected results.

Also, __contains__ should be efficient because it runs every time you use in on your object.

python
class BadExample:
    def __contains__(self, item):
        print(f"Checking {item}")  # Missing return statement

obj = BadExample()
print('test' in obj)  # This prints None, which is treated as False

class GoodExample:
    def __contains__(self, item):
        return item == 'test'

obj2 = GoodExample()
print('test' in obj2)  # True
print('other' in obj2)  # False
Output
Checking test False True False
📊

Quick Reference

  • Purpose: Customize in keyword behavior for your class.
  • Signature: def __contains__(self, item) -> bool
  • Return: True if item found, else False.
  • Use case: Check membership in custom containers.

Key Takeaways

Implement __contains__ to control how 'in' works with your objects.
Always return True or False from __contains__.
Use __contains__ for efficient membership checks in custom classes.
Remember __contains__ takes self and the item to check as parameters.
Test your __contains__ method to avoid unexpected behavior.