Is there a way to check if two object contain the same values in each of their variables in python?

Aufwind picture Aufwind · Jun 21, 2011 · Viewed 22.7k times · Source

How do I check if two instances of a

class FooBar(object):
    __init__(self, param):
        self.param = param
        self.param_2 = self.function_2(param)
        self.param_3 = self.function_3()

are identical? By identical I mean they have the same values in all of their variables.

a = FooBar(param)
b = FooBar(param)

I thought of

if a == b:
    print "a and b are identical"!

Will this do it without side effects?

The background for my question is unit testing. I want to achieve something like:

self.failUnlessEqual(self.my_object.a_function(), another_object)

Answer

AJ. picture AJ. · Jun 21, 2011

If you want the == to work, then implement the __eq__ method in your class to perform the rich comparison.

If all you want to do is compare the equality of all attributes, you can do that succinctly by comparison of __dict__ in each object:

class MyClass:

    def __eq__(self, other) : 
        return self.__dict__ == other.__dict__