Testing for reference equality in Python

Question:

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.

Asked By: Adam Parkin

||

Answers:

Thats the is operator

print f1 is f2

Use the is keyword.

print f1 is f2

Some interesting things (that are implementation dependent I believe, but they are true in CPython) with the is keyword is that None, True, and False are all singleton instances. So True is True will return True.

Strings are also interned in CPython, so 'hello world' is 'hello world' will return True (you should not rely on this in normal code).

Answered By: Jonathan Sternberg

f1 is f2 checks if two references are to the same object. Under the hood, this compares the results of id(f1) == id(f2) using the id builtin function, which returns a integer that’s guaranteed unique to the object (but only within the object’s lifetime).

Under CPython, this integer happens to be the address of the object in memory, though the docs mention you should pretend you don’t know that (since other implementation may have other methods of generating the id).

Answered By: Eli Collins
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.