What is the difference between "a is b" and "id(a) == id(b)" in Python? What is the difference between "a is b" and "id(a) == id(b)" in Python? python python

What is the difference between "a is b" and "id(a) == id(b)" in Python?


>>> b.test is a.testFalse>>> a.test is a.testFalse

Methods are created on-the-fly each time you look them up. The function object (which is always the same object) implements the descriptor protocol and its __get__ creates the bound method object. No two bound methods would normally be the same object.

>>> id(a.test) == id(b.test)True>>> a.test is b.testFalse

This example is deceptive. The result of the first is only True by coincidence. a.test creates a bound method and it's garbage collected after computing id(a.test) because there aren't any references to it. (Note that you quote the documentation saying that an id is "unique and constant for this object during its lifetime" (emphasis mine).) b.test happens to have the same id as the bound method you had before and it's allowed to because no other objects have the same id now.

Note that you should seldom use is and even less often use id. id(foo) == id(bar) is always wrong.


Regarding your new example, hopefully you get what it does now:

>>> new_improved_test_method = lambda: None>>> a.test = new_improved_test_method>>> a.test is a.testTrue

In this case, we aren't making methods on the fly from functions on the class automatically binding self and returning bound method objects. In this case, you simply store a function as an instance attribute. Nothing special happens on lookup (descriptors only get called when you look up a class attribute), so every time you look up the attribute, you get the original object you stored.