>> from collections import OrderedDic...">

Very strange "there is" operator behavior with methods

Why is the first result False if it was not True ?

 >>> from collections import OrderedDict >>> OrderedDict.__repr__ is OrderedDict.__repr__ False >>> dict.__repr__ is dict.__repr__ True 
+47
python methods python-internals
Jun 23 '14 at 2:00
source share
2 answers

For user-defined functions in Python 2, limitless and related methods are created on demand using the handle protocol ; OrderedDict.__repr__ is such a method object since the wrapped function is implemented as a pure-Python function.

The descriptor protocol will call the __get__ method for objects that support it, so __repr__.__get__() is called whenever you try to access OrderedDict.__repr__ ; for None classes (no instance) and the class object itself. Since you get a new method object every time you call the __get__ method, is fails. This is not the same method object.

dict.__repr__ not a custom Python function, but the C function and its __get__ descriptor essentially just returns self when accessing the class . Access to the attribute gives the same object every time, so is works:

 >>> dict.__repr__.__get__(None, dict) is dict.__repr__ # None means no instance True 

Methods have an __func__ attribute referencing a wrapped function, use this for authentication:

 >>> OrderedDict.__repr__ <unbound method OrderedDict.__repr__> >>> OrderedDict.__repr__.__func__ <function __repr__ at 0x102c2f1b8> >>> OrderedDict.__repr__.__func__.__get__(None, OrderedDict) <unbound method OrderedDict.__repr__> >>> OrderedDict.__repr__.__func__ is OrderedDict.__repr__.__func__ True 

Python 3 eliminates unrelated methods, function.__get__(None, classobj) returns the function object itself (so it behaves like a dict.__repr__ ). But you will see the same behavior with related methods, methods obtained from the instance.

+56
Jun 23 '14 at 2:05
source share

Two OrderedDict.__repr__ not bound to the same object. If you try:

  OrderedDict.__repr__ == OrderedDict.__repr__ 

You will see that they have the same meaning.

+1
Jun 23 '14 at 2:04
source share



All Articles