Override Python's 'in' operator?
Asked Answered
F

3

290

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:
    ...

See also What does __contains__ do, what can call __contains__ function for the corresponding question about what __contains__ does.

Funderburk answered 7/2, 2010 at 14:8 Comment(1)
I was actually searching how to override the is and is not operators. Like a query = tinydb.Query().field == value, to also be able to write Query().field is not None. But it seems I'm left with __eq__ and __ne__ for the time being, which leads to the unpythonic Query().field != None. (sarc)Tamikatamiko
F
358

MyClass.__contains__(self, item)

Farewell answered 7/2, 2010 at 14:10 Comment(0)
B
276

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__.

Battaglia answered 7/2, 2010 at 21:26 Comment(1)
Doesn't work for me :/Sheepherder
C
3

Another way of having desired logic is to implement __iter__.

If you don't overload __contains__ python would use __iter__ (if it's overloaded) to check whether or not your data structure contains specified value.

Calcaneus answered 31/12, 2022 at 22:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.