Question

I have run into problems comparing complex objects in Python, in cases where someone does, effectively object_a = object_b followed by if object_a == object_b:. My usual 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_pointer = str(a)
>>> b_pointer = str(b)
>>> a
<__main__.Thing instance at 0x16c0098>
>>> b
<__main__.Thing instance at 0x16c0098>
>>> a == b
True

Is there a better way? Is there a case where this may not work?

Was it helpful?

Solution

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.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top