Implement membership checks for custom containers using __contains__().
How It Works
The in operator consults __contains__() when available. Otherwise Python can fall back to iteration or old-style sequence access. A membership method should return a truthy or falsy answer without surprising side effects.
Membership can be optimized with internal sets when frequent lookups matter.
Step-by-Step Example
class WordDictionary:
def __init__(self, words):
self.words = set(words)
def __contains__(self, word):
return word.lower() in self.words
word_dictionary = WordDictionary({"python", "library"})
print("PYTHON" in word_dictionary)
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
True
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Implement case-insensitive membership for a set of labels.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Recursively using the in operator on the same object inside __contains__().
- Assuming membership always checks identity rather than container-defined equality.
Key Takeaways
- Implement membership checks for custom containers using __contains__().
- The in operator consults __contains__() when available.
- Membership can be optimized with internal sets when frequent lookups matter.