Why does function descriptor create new bound method each time

52 Views Asked by At

Could you explain why new bound method is created each time when trying to access same method of the same class instance?

class MyClass:
    def my_method(self):
        print(f"Called bounded to {self}")


m_unbound = MyClass.my_method
print(f"{type(m_unbound)} {hash(m_unbound)}")  # <class 'function'> 8783579798336
m_unbound(None)

mc = MyClass()
m1 = mc.my_method
print(f"{type(m1)} {hash(m1)}")  # <class 'method'> 122173
m1()

m2 = mc.my_method  # THOUGHT IT WOULD BE THE SAME OBJECT AS m1
print(f"{type(m2)} {hash(m2)}")  # <class 'method'> 122173
m2()

print(m1 == m2)  # True
print(m1 is m2)  # False, why is so?
print(id(m1) == id(m2))  # False, equivalent of the above

I do not understand why new bound method object is created each time if underlying instance still stays the same (as well as target function)

print(m1.__self__ is m2.__self__)  # True, bound instance is the same
print(m1.__func__ is m2.__func__)  # True, target function is the same
print(m2.__func__ is m_unbound)  # True
0

There are 0 best solutions below