This bit of Python has me puzzled.
class my_class(object):
def f():
return 1
c = my_class()
f1 = c.f
f2 = c.f
assert not f1 is f2
assert id(f1) != id(f2)
assert f1 == f2
All three asserts pass. The first two are equivalent to each other, but I expected both to fail.
This seems very strange to me. Is Python really creating new, bound, member function objects whenever I call c.f
? Why would it do that?
OK - looking here, I guess the answer to my first question is yes. But still, this business of having different ids with consistent ==
seems completely strange in this context. For containers, sure, I want divergence between is
and ==
(i.e two distinct container objects that contain equivalent data). But for member functions, it seems like is
and ==
ought to be equivalent.
Can anyone motivate this bit of Python design for me?
EDIT : Upon further reflection, this makes sense to me. In order for the memory footprint of an object to be small, the bound functions have to be created upon request, and thus will be distinct objects for each request.