user1474424
user1474424

Reputation: 667

How can you implement a custom comparator for 'in' using python

If i had a class like this:

class foo(object):
    def __init__(self, x, y, z):
         self.x = x
         self.y = y
         self.z = z

In a list like this:

list = [foo(1, 2, 3), foo(4, 5, 6), foo(7, 8, 9)]

How could i create a custom test for 'in' such that it checks only x and z values such that this:

new_foo = foo(1,8,3)
if new_foo in list:
    print True
else:
    print False

Would print True

Upvotes: 1

Views: 497

Answers (1)

BrenBarn
BrenBarn

Reputation: 251383

Using in on lists tests using equality, so you need to define an __eq__ method: see the documentation. You will also need to define a __hash__ method to ensure that your objects compare equal in a consistent manner if they have mutable state. For instance:

class foo(object):
    def __init__(self, x,y,z):
         self.x = x
         self.y = y
         self.z = z

    def __eq__(self, other):
        return (self.x, self.z) == (other.x, other.z)

    def __hash__(self):
        return hash((self.x, self.z))

You should think carefully about whether you really want to do this, though. It defines a notion of equality which will apply in all situations where equality is tested. So if you do what you ask for in your post, then foo(1,2,3) == foo(1,8,3) will be true in general, not just when using in.

Upvotes: 6

Related Questions