0

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
GopherM
  • 352
  • 2
  • 8
  • 1
    Presumably, the cost of caching each `method` instance that gets created was deemed higher than the cost of simply recreating a new instance on the fly. – chepner Jan 07 '23 at 13:28
  • 1
    That is, it's not *required* to create a new method each time, but there's no obvious *benefit* to avoiding it. – chepner Jan 07 '23 at 13:48

0 Answers0