Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a == b is false, but id(a) == id(b) is true?

Ran into the following:

>>> class A:
...     def __str__(self):
...             return "some A()"
... 
>>> class B(A):
...     def __str__(self):
...             return "some B()"
... 
>>> print A()
some A()
>>> print B()
some B()
>>> A.__str__ == B.__str__
False # seems reasonable, since each method is an object
>>> id(A.__str__)==id(B.__str__)
True # what?!

What's going on here?

like image 800
bb. Avatar asked Feb 23 '10 15:02

bb.


People also ask

What is id () Python?

Definition and Usage. The id() function returns a unique id for the specified object. All objects in Python has its own unique id. The id is assigned to the object when it is created. The id is the object's memory address, and will be different for each time you run the program. (

What is the meaning of == in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and !=

How do you compare two functions in Python?

Python - cmp() function cmp() is an in-built function in Python, it is used to compare two objects and returns value according to the given values. It does not return 'true' or 'false' instead of 'true' / 'false', it returns negative, zero or positive value based on the given input.

How do you check if two variables are true in Python?

The is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test returns False if they are not the same object, even if the two objects are 100% equal. Use the == operator to test if two variables are equal.


2 Answers

As the string id(A.__str__) == id(B.__str__) is evaluated, A.__str__ is created, its id taken, and then garbage collected. Then B.__str__ is created, and happens to end up at the exact same address that A.__str__ was at earlier, so it gets (in CPython) the same id.

Try assigning A.__str__ and B.__str__ to temporary variables and you'll see something different:

>>> f = A.__str__
>>> g = B.__str__
>>> id(f) == id(g)
False

For a simpler example of this phenomenon, try:

>>> id(float('3.0')) == id(float('4.0'))
True
like image 108
Mark Dickinson Avatar answered Oct 09 '22 15:10

Mark Dickinson


The following works:

>>> id(A.__str__.im_func) == id(A.__str__.im_func)
True
>>> id(B.__str__.im_func) == id(A.__str__.im_func)
False
like image 21
honzas Avatar answered Oct 09 '22 13:10

honzas