How to find the definition of an operator in the python source code?
I became curious about the implementation of the "in" ( __contains__
?) operator in python due to this SO question. I downloaded the source code and tried to grep, browse, etc. to find some base definition of it, but I haven't been successful. Could someone show me a way to find it?
Of course a general approach to finding that kind of thing would be best so anyone like me can learn to fish for next time.
I'm using 2.7 but if the process is totally different for 3.x, that would be nice to have both techniques.
I think the implementation starts in PySequence_Contains
in Objects/abstract.c
. I found it by looking through the implementation of operator.contains
in Modules/operator.c
, which wraps all the native operators in Python functions.
Based on Inerdial's push in the right direction, here is how I dug down to it. Any feedback on a better way to go about this would be appreciated.
ack --type=cc __contains__
leads to operator.c
spam2(contains,__contains__,
"contains(a, b) -- Same as b in a (note reversed operands).")
which renames "contains" to "op_contains" which in turn points to PySequence_Contains (not in this file)
ack --type=cc PySequence_Contains
leads to the definition in abstract.c (just the return below)
result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
which leads to _PySequence_IterSearch (just the comparison below)
cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
which leads to PyObject_RichCompareBool (not in this file)
ack --type=cc PyObject_RichCompareBool
leads to the definition in object.c where I finally find the implementation of the comparison that is doing identity check before the actual equality check (my original question about the comparison).
/* Quick result when objects are the same.
Guarantees that identity implies equality. */
if (v == w) {
if (op == Py_EQ)
return 1;
else if (op == Py_NE)
return 0;
}
链接地址: http://www.djcxy.com/p/57314.html