Why is the first result False
, should it not be True
?
>>> from collections import OrderedDict
>>> OrderedDict.__repr__ is OrderedDict.__repr__
False
>>> dict.__repr__ is dict.__repr__
True
Why is the first result False
, should it not be True
?
>>> from collections import OrderedDict
>>> OrderedDict.__repr__ is OrderedDict.__repr__
False
>>> dict.__repr__ is dict.__repr__
True
The two
OrderedDict.__repr__
are not bound to the same object. If you try:you'll see that they have the same value.
For user-defined functions, in Python 2 unbound and bound methods are created on demand, through the descriptor protocol;
OrderedDict.__repr__
is such a method object, as the wrapped function is implemented as a pure-Python function.The descriptor protocol will call the
__get__
method on objects that support it, so__repr__.__get__()
is called whenever you try to accessOrderedDict.__repr__
; for classesNone
(no instance) and the class object itself are passed in. Because you get a new method object each time the function__get__
method is invoked,is
fails. It is not the same method object.dict.__repr__
is not a custom Python function but a C function, and its__get__
descriptor method essentially just returnsself
when accessed on the class. Accessing the attribute gives you the same object each time, sois
works:Methods have a
__func__
attribute referencing the wrapped function, use that to test for identity:Python 3 does away with unbound methods,
function.__get__(None, classobj)
returns the function object itself (so it behaves likedict.__repr__
does). But you will see the same behaviour with bound methods, methods retrieved from an instance.