Search code examples
pythoncontains

Overriding a class to be left hand side of in operator


Apparently the __contains__ special method allows to implement the in evaulation when the object with the method is on the right hand side of it. I have a piece of code where the in must be implemented by the left hand operand. How do I go about it?


Solution

  • I was able to get this to work by overriding __eq__.

    Consider the code "value in some_list". It will iterate through some_list until it finds value. But how does it know if it found value? By comparing it. That's what you want to override.

    class Twenty(object):
        def __init__(self):
            self.x = 20
                
        def __eq__(self, y):
            print "comparing", self.x, "to", y
            return self.x == y
        
    value = Twenty()
    assert value in [10, 20, 30]
    assert value not in [1, 2, 3]
    

    output

    comparing 20 to 10
    comparing 20 to 20
    comparing 20 to 1
    comparing 20 to 2
    comparing 20 to 3