Override Python's 'in' operator?
To override the 'in' operator, define the __contains__ method in your class. This method customizes the way Python checks for membership.
Here's a simple example:
Customizing membership testing with contains
Use the __contains__ method to customize membership testing according to your class's purpose. Here's an example where we use it to check if a custom object is in a collection:
When contains isn't enough
If __contains__ isn't defined, Python defaults to __iter__, using it to check for membership. This is particularly useful for large data structures, but may not be the most efficient method for all data types.
Complex membership conditions
The __contains__ method can handle complex conditions beyond checking for simple membership:
Don't forget to test!
After defining __contains__, test various cases to confirm your in operator behaves correctly.
Keeping it Pythonic
When crafting your __contains__ method, remember the Zen of Python. Your __contains__ should leave little room for interpretation and should behave predictably.
Was this article helpful?