Override Python's 'in' operator?

PythonOperator OverloadingOperatorsIn Operator

Python Problem Overview


If I am creating my own class in Python, what function should I define so as to allow the use of the in operator, e.g.

class MyClass(object):
    ...

m = MyClass()

if 54 in m:
    ...

Python Solutions


Solution 1 - Python

Solution 2 - Python

A more complete answer is:

class MyClass(object):

    def __init__(self):
        self.numbers = [1,2,3,4,54]

    def __contains__(self, key):
        return key in self.numbers

Here you would get True when asking if 54 was in m:

>>> m = MyClass()
>>> 54 in m
True  

See documentation on overloading __contains__.

Solution 3 - Python

You might also want to take a look at an infix operator override framework I was able to use to create a domain-specific language:

http://code.activestate.com/recipes/384122/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionastrofrogView Question on Stackoverflow
Solution 1 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - PythonpthulinView Answer on Stackoverflow
Solution 3 - Pythonuser250828View Answer on Stackoverflow