[英]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 . 由于这个SO问题 ,我对python中“in”(
__contains__
?)运算符的实现感到好奇。 I downloaded the source code and tried to grep, browse, etc. to find some base definition of it, but I haven't been successful. 我下载了源代码并试图grep,浏览等找到它的一些基本定义,但我还没有成功。 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. 我正在使用2.7,但如果3.x的过程完全不同,那么两种技术都会很好。
I think the implementation starts in PySequence_Contains
in Objects/abstract.c
. 我认为实现从
Objects/abstract.c
中的PySequence_Contains
开始。 I found it by looking through the implementation of operator.contains
in Modules/operator.c
, which wraps all the native operators in Python functions. 我通过查看
Modules/operator.c
的operator.contains
的实现找到了它,它包装了Python函数中的所有本机操作符。
Based on Inerdial's push in the right direction, here is how I dug down to it. 基于Inerdial在正确方向上的推动,这是我如何挖掘它。 Any feedback on a better way to go about this would be appreciated.
任何关于更好的方式的反馈将不胜感激。
ack --type=cc __contains__
leads to operator.c 导致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) 它将“包含”重命名为“op_contains”,后者又指向PySequence_Contains(不在此文件中)
ack --type=cc PySequence_Contains
leads to the definition in abstract.c (just the return below) 导致abstract.c中的定义(只是下面的返回)
result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
which leads to _PySequence_IterSearch (just the comparison below) 这导致_PySequence_IterSearch(只是下面的比较)
cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
which leads to PyObject_RichCompareBool (not in this file) 这导致PyObject_RichCompareBool(不在此文件中)
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). 导致在object.c中的定义,我终于找到了在实际的相等检查之前进行身份检查的比较的实现(我关于比较的原始问题)。
/* 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.