What is the pythonic way to test whether two objects are the same, not just equal

Question:

My solution has been to make the object’s address into a string, which should always be unique.

Below is a case where it works both ways, comparing the objects and comparing the values of str(object_a) and str(object_b).

>>> class Thing:
>>>     def __init__(self):
>>>         self.x = 0
>>>         return
>>>
>>> a = Thing()
>>> b = a
>>> b == a
True
>>> a_string = str(a)
>>> b_string = str(b)
>>> a_string
<__main__.Thing instance at 0x16c0098>
>>> b_string
<__main__.Thing instance at 0x16c0098>
>>> a_string == b_string
True

What is the pythonic way?

Asked By: anon

||

Answers:

The simple sure-fire way to check for equality is ==:

a == b

The simple sure-fire way to check to see if they have the same identity is is:

a is b

The 2nd way (is) performs the same check that you intend str(a)==str(b) to perform.

Answered By: Robᵩ

With your code you aren’t comparing two objects in a faster way, but just asking if your variables points to the same object, which is quite different.

Anyway, the pythonic way to do it is not casting pointers to string, but using operator “is”:

>>> a is b
True
>>> b is A
True
Answered By: dbra