Search code examples
pythonmagic-methodsgetattr

What are the names of the magic methods for the operators "is" and "in"?


I would like to make bool binary operations using the magic methods for these operators. For example, I can get a < b as getattr(a, '__lt__')(b) or a == b as getattr(a, '__eq__')(b).

Can I get a in b and a is b in such a way?


Solution

  • in is __contains__ and is does not have a dunder method. I strongly suggest you use the functions in the operator module:

    a < b  => operator.lt(a, b)
    a == b => operator.eq(a, b)
    a in b => operator.contains(a, b)
    a is b => operator.is_(a, b)