The Python Oracle

Override Python's 'in' operator?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping

--

Chapters
00:00 Override Python'S 'In' Operator?
00:17 Accepted Answer Score 359
00:24 Answer 2 Score 280
00:49 Answer 3 Score 3
01:08 Thank you

--

Full question
https://stackoverflow.com/questions/2217...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #operatoroverloading #operators #inoperator

#avk47



ACCEPTED ANSWER

Score 359


MyClass.__contains__(self, item)




ANSWER 2

Score 280


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




ANSWER 3

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