Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for reference equality in Python

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.

like image 649
Adam Parkin Avatar asked Sep 01 '11 17:09

Adam Parkin


People also ask

Which is used to check the reference equality in Python?

== operator is used to check whether two variables reference objects with the same value.

How do you check if an object has equality in Python?

Every object has an identity, a type and a value. == and is are two ways to compare objects in Python. == compares 2 objects for equality, and is compares 2 objects for identity.

What is === in Python?

=== <— This is a question . It asks if the right operand is the same as the left operand. Examples: 10 === 10 <— is left 10 the same as right 10 ? .


2 Answers

Thats the is operator

print f1 is f2 
like image 111
SingleNegationElimination Avatar answered Oct 06 '22 19:10

SingleNegationElimination


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).

like image 31
Eli Collins Avatar answered Oct 06 '22 18:10

Eli Collins