user3002473
user3002473

Reputation: 5074

Python "magic method" for customizing the behaviour of the in operator

I know that there are a number of magic methods in python that affect the way an object behaves in certain situations (like defining __cmp__(self, other) to change the way it works when compared with another instance of itself), but I was wondering, is there a way to alter the behavior of how the object is called in an 'in' operator?

if thing in custom_object:
    call_the_object_in_a_customized_way()

Would there be any way of doing this?

Upvotes: 0

Views: 1203

Answers (2)

aIKid
aIKid

Reputation: 28352

Define the function __contains__ for this. It's invoked when you use the in operator.

Demo:

>>> class Test:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
    def __contains__(self, item):
        return item in (self.a, self.c)


>>> a = Test(1, 2, 3)
>>> 1 in a
True
>>> 3 in a
True
>>> 2 in a
False

Upvotes: 4

Eric
Eric

Reputation: 97691

__contains__ is the method you're looking for

From this page:

For user-defined classes which define the __contains__() method, x in y is true if and only if y.__contains__(x) is true.

For user-defined classes which do not define __contains__() but do define __iter__(), x in y is true if some value z with x == z is produced while iterating over y. If an exception is raised during the iteration, it is as if in raised that exception.

Lastly, the old-style iteration protocol is tried: if a class defines __getitem__(), x in y is true if and only if there is a non-negative integer index i such that x == y[i], and all lower integer indices do not raise IndexError exception. (If any other exception is raised, it is as if in raised that exception).

Upvotes: 8

Related Questions