Testing for reference equality in Python

Adam Parkin picture Adam Parkin · Sep 1, 2011 · Viewed 14.5k times · Source

Say I have a class in Python that has an eq method defined for comparing attributes for equality:

class Foo(object):
    # init code...

    def __eq__(self, other):
        # usual eq code here....

How can I then compare two instances of Foo for reference equality (that is test if they are the same instance)? If I do:

f1 = Foo()
f2 = Foo()
print f1 == f2

I get True even though they are different objects.

Answer

SingleNegationElimination picture SingleNegationElimination · Sep 1, 2011

Thats the is operator

print f1 is f2