Override Python's 'in' operator?

90,604

Solution 1

MyClass.__contains__(self, item)

Solution 2

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

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/

Share:
90,604

Related videos on Youtube

astrofrog
Author by

astrofrog

Updated on September 21, 2021

Comments

  • astrofrog
    astrofrog over 2 years

    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:
        ...
    
    • Tomasz Gandor
      Tomasz Gandor almost 7 years
      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)
  • Peter Hansen
    Peter Hansen about 14 years
    @pthulin, yours may be "more complete" in terms of code, but Ignacio's links to the documentation, which is always a big plus for some.
  • Zoran Pavlovic
    Zoran Pavlovic almost 12 years
    @PEter. YEah, but some of us prefer a nice, visual representation of the answer. Ignacio's did little to benefit the question other than direct us here first instead of google, no thank you.
  • Peter Hansen
    Peter Hansen over 11 years
    Zoran, I agree, and I even upvoted this answer and not the other. I'm just pointing out that a truly good answer should always link to docs, if available.
  • demongolem
    demongolem over 11 years
    All, links die and that is why Ignacio's answer is shaky on SO. Links + example is the best and that is why a combination of the two answers we are talking about is best.
  • wizzwizz4
    wizzwizz4 about 7 years
    @demongolem The official Python documentation will die with or after the interpreter becomes undownloadable. And it isn't a link-only answer; I came to this page looking for the answer and found it without clicking on any further links (i.e. the prototype was sufficient). I do agree in principle, but imho that doesn't apply here.