Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the `==` operator not equivalent to the `is` operator? (Python)

I noticed I can use the == operator to compare all the native data types (integers, strings, booleans, floating point numbers etc) and also lists, tuples, sets and dictionaries which contain native data types. In these cases the == operator checks if two objects are equal. But in some other cases (trying to compare instances of classes I created) the == operator just checks if the two variables reference the same object (so in these cases the == operator is equivalent to the is operator)

My question is: When does the == operator do more than just comparing identities?

EDIT: I'm using Python 3

like image 691
snakile Avatar asked Sep 05 '10 20:09

snakile


People also ask

Is not equal to operator in Python?

In Python !=is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal.

How is the operator different from is in Python?

The is operator compares the identity of two objects while the == operator compares the values of two objects. There is a difference in meaning between equal and identical. And this difference is important when you want to understand how Python's is and == comparison operators behave.

What is not equal to operator used for?

The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .


1 Answers

In Python, the == operator is implemented in terms of the magic method __eq__, which by default implements it by identity comparison. You can, however, override the method in order to provide your own concept of object equality. Note, that if you do so, you will usually also override at least __ne__ (which implements the != operator) and __hash__, which computes a hash code for the instance.

I found it very helpful, even in Python, to make my __eq__ implementations comply with the rules set out in the Java language for implementations of the equals method, namely:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

the last one should probably replace null with None, but the rules are not as easy here in Python as in Java.

like image 69
Dirk Avatar answered Oct 11 '22 22:10

Dirk