The __contains__ method defines what the in and not in operators do for your class. When you write x in obj, Python calls type(obj).__contains__(obj, x) and converts the result to a boolean. Implement it to give custom containers fast, meaningful membership tests.
If a class has no __contains__, Python falls back to iterating with __iter__, and then to __getitem__ with integers starting at 0, so many classes work with in without it.
not in is simply the negation of the same call, so you only write one method. The method should return a truthy or falsy value; return a real bool for clarity.
__contains__ does not have to look anything up. It can compute the answer, which is useful for ranges and conditions:
This is O(1) and uses no memory for the values, in the same spirit as range, which supports in without building a list.
Python tries these strategies in order:
__contains__, if defined.__iter__, comparing each item with == (or identity) until one matches.__getitem__ with 0, 1, 2 and so on until IndexError.This works but is linear. When the data lives in a set or dictionary, define __contains__ to delegate to it and get constant-time lookups.
| Method | Used by | Purpose |
|---|---|---|
__contains__ | in, not in | Membership test |
__iter__ | for, list(), unpacking | Iterate over items |
__len__ | len() | Number of items |
__getitem__ | obj[key] | Lookup by key or index |
You can inherit from collections.abc.Collection, Set or Mapping and implement the abstract methods. The base class then supplies many helper methods for free.
A short test with unittest or pytest documents the contract, including the negative case and the not in form:
Check edge cases such as bounds, empty containers and unexpected types, because callers expect in to be predictable.
in is expected to be cheap and read-only.__contains__ consistent with __iter__: if iteration yields an item, item in obj should be true.False instead, or handle TypeError for unhashable values when you delegate to a set."ab" in "cab" is a substring test, not an element test. That is the behaviour of str.__contains__.NaN: float("nan") in [float("nan")] is False for a different object but True if it is the same object, because containers check identity before equality.in operator?No. Python falls back to iteration or __getitem__. Define it when you want a faster or custom test.
not in call?It calls the same __contains__ method and negates the result.
Yes, return True or False. Python converts other values with bool(), but a real boolean avoids surprises.
in work on dictionary keys of my class?Delegate to the internal dict: return key in self._data. For a Mapping subclass, in checks keys.
__contains__ powers in and not in. Delegate to a set or dict for fast lookups, compute the answer for rule-based containers, keep it consistent with __iter__, and rely on the fallback only when linear scanning is acceptable.