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

Viewed 37917

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)
6 Answers

For python 3.7 onwards you can also use dataclass to check exactly what you want very easily. For example:

from dataclasses import dataclass

@dataclass
class FooBar:
    param: str
    param2: float
    param3: int

a = Foobar("test_text",2.0,3)
b = Foobar("test_text",2.0,3)

print(a==b)

would return True

According to Learning Python by Lutz, the "==" operator tests value equivalence, comparing all nested objects recursively. The "is" operator tests whether two objects are the same object, i.e. of the same address in memory (same pointer value). Except for cache/reuse of small integers and simple strings, two objects such as x = [1,2] and y = [1,2] are equal "==" in value, but y "is" x returns false. Same true with two floats x = 3.567 and y = 3.567. This means their addresses are different, or in other words, hex(id(x)) != hex(id(y)).

For class object, we have to override the method __eq__() to make two class A objects like x = A(1,[2,3]) and y = A(1,[2,3]) "==" in content. By default, class object "==" resorts to comparing id only and id(x) != id(y) in this case, so x != y. In summary, if x "is" y, then x == y, but opposite is not true.

If this is something you want to use in your tests where you just want to verify fields of simple object to be equal, look at compare from testfixtures:

from testfixtures import compare

compare(a, b)
Related