有没有一种方法可以看到python中内置函数是如何工作的?我的意思不仅仅是如何使用它们,还包括它们是如何构建的,排序或枚举等背后的代码是什么?
当前回答
我不得不挖掘一点来找到以下内置函数的源代码,因为搜索会产生成千上万的结果。(祝你能找到任何一个来源)
不管怎样,所有这些函数都是在bltinmodule.c中定义的。
内置来源:https://github.com/python/cpython/blob/master/Python/bltinmodule.c 对于内置类型: https://github.com/python/cpython/tree/master/Objects
其他回答
正如@Jim提到的,这里描述了文件组织。为便于发现而转载:
For Python modules, the typical layout is: Lib/<module>.py Modules/_<module>.c (if there’s also a C accelerator module) Lib/test/test_<module>.py Doc/library/<module>.rst For extension-only modules, the typical layout is: Modules/<module>module.c Lib/test/test_<module>.py Doc/library/<module>.rst For builtin types, the typical layout is: Objects/<builtin>object.c Lib/test/test_<builtin>.py Doc/library/stdtypes.rst For builtin functions, the typical layout is: Python/bltinmodule.c Lib/test/test_builtin.py Doc/library/functions.rst Some exceptions: builtin type int is at Objects/longobject.c builtin type str is at Objects/unicodeobject.c builtin module sys is at Python/sysmodule.c builtin module marshal is at Python/marshal.c Windows-only module winreg is at PC/winreg.c
我不得不挖掘一点来找到以下内置函数的源代码,因为搜索会产生成千上万的结果。(祝你能找到任何一个来源)
不管怎样,所有这些函数都是在bltinmodule.c中定义的。
内置来源:https://github.com/python/cpython/blob/master/Python/bltinmodule.c 对于内置类型: https://github.com/python/cpython/tree/master/Objects
让我们直接回答你的问题。
寻找内置Python函数的源代码?
源代码位于cpython/Python/bltinmodule.c
要在GitHub存储库中找到源代码,请点击这里。您可以看到所有内置函数都以builtin_<name_of_function>开头,例如,sorted()是在builtin_sorted中实现的。
为了让你高兴,我将发布sorted()的实现:
builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *newlist, *v, *seq, *callable;
/* Keyword arguments are passed through list.sort() which will check
them. */
if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
return NULL;
newlist = PySequence_List(seq);
if (newlist == NULL)
return NULL;
callable = _PyObject_GetAttrId(newlist, &PyId_sort);
if (callable == NULL) {
Py_DECREF(newlist);
return NULL;
}
assert(nargs >= 1);
v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Py_DECREF(callable);
if (v == NULL) {
Py_DECREF(newlist);
return NULL;
}
Py_DECREF(v);
return newlist;
}
您可能已经注意到,这不是Python代码,而是C代码。
这是一个食谱回答补充@Chris的回答,CPython已经转移到GitHub, Mercurial存储库将不再更新:
必要时安装Git。 Git克隆https://github.com/python/cpython.git 代码将检出到名为cpython -> cd cpython的子目录 假设我们正在寻找print()的定义… egrep——color=always -R 'print' | less -R 啊哈!参见Python/bltinmodule.c -> builtin_print()
享受。
iPython shell让这变得很简单:function?会给你文件。函数? ?还显示了代码。但这只适用于纯python函数。
然后您可以随时下载(c)Python的源代码。
如果你对核心功能的python实现感兴趣,可以看看PyPy源代码。