Python › Magic Methods & Operator Overloading

How does __contains__ let you customize the behavior of the 'in' operator?

Intermediate

Answer

Defining __contains__(self, item) lets Python call it directly when evaluating `item in obj`, instead of falling back to iterating the whole object with __iter__ or __getitem__. This can be much faster for containers with efficient membership tests, like a class backed by a set or a database query.
class UserGroup:
    def __init__(self, user_ids):
        self._ids = set(user_ids)  # O(1) lookup
    def __contains__(self, user_id):
        return user_id in self._ids

group = UserGroup([1,2,3])
print(2 in group)  # True, O(1) via set
Real-world example A permissions class backed by a set of allowed role IDs implements __contains__ so `if role in permissions:` checks run in constant time instead of scanning a list.

Common follow-ups: What's the fallback behavior if __contains__ isn't defined?;How does this interact with __iter__ for custom iterables?