正在寻找内置 Python 函数的源代码?
- 2024-12-02 08:41:00
- admin 原创
- 162
问题描述:
有没有办法查看 Python 中内置函数的工作原理?我的意思不仅仅是如何使用它们,还包括它们是如何构建的,排序或枚举等背后的代码是什么……?
解决方案 1:
由于 Python 是开源的,因此您可以阅读源代码。
要找出特定模块或函数在哪个文件中实现,通常可以打印__file__
属性。或者,您可以使用模块,请参阅文档中的检索源代码inspect
部分。inspect
对于内置类和方法,情况就没那么简单了,因为inspect.getfile
和inspect.getsource
将返回类型错误,指出该对象是内置的。但是,许多内置类型都可以在Objects
Python 源代码主干的子目录中找到。例如,请参阅此处了解枚举类的实现,或此处了解类型的实现list
。
解决方案 2:
我不得不花点功夫去寻找以下内容的来源,Built-in Functions
因为搜索会产生数千个结果。(希望你能找到其中任何一个的来源)
无论如何,所有这些函数都是在bltinmodule.c
以开头的函数中定义的builtin_{functionname}
内置源代码:https://github.com/python/cpython/blob/master/Python/bltinmodule.c
对于内置类型:
https ://github.com/python/cpython/tree/master/Objects
解决方案 3:
这里有一个食谱答案来补充@Chris' 的答案,CPython 已经移至 GitHub 并且 Mercurial 存储库将不再更新:
如果需要,安装 Git。
git clone https://github.com/python/cpython.git
cpython
代码将签出到名为-> 的子目录cd cpython
假设我们正在寻找
print()
...的定义egrep --color=always -R 'print' | less -R
啊哈!参见
Python/bltinmodule.c
->builtin_print()
享受。
解决方案 4:
iPython shell使这变得简单:function?
将为您提供文档。function??
还显示代码。但这仅适用于纯 Python 函数。
然后您可以随时下载(c)Python 的源代码。
如果您对核心功能的 Python 实现感兴趣,请查看PyPy源代码。
解决方案 5:
2 种方法,
您可以使用以下代码片段检查用法
help()
您可以使用以下方法检查这些模块的隐藏代码
inspect
1)检查:
使用inpsect模块来探索你想要的代码...
注意:你只能探索你导入的模块(又名)包的代码
例如:
>>> import randint
>>> from inspect import getsource
>>> getsource(randint) # here i am going to explore code for package called `randint`
2)帮助():
您可以简单地使用help()
命令来获取有关内置函数及其代码的帮助。
例如:如果你想查看 str() 的代码,只需输入 -help(str)
它会像这样返回,
>>> help(str)
Help on class str in module __builtin__:
class str(basestring)
| str(object='') -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.
|
| Method resolution order:
| str
| basestring
| object
|
| Methods defined here:
|
| __add__(...)
| x.__add__(y) <==> x+y
|
| __contains__(...)
| x.__contains__(y) <==> y in x
|
| __eq__(...)
| x.__eq__(y) <==> x==y
|
| __format__(...)
| S.__format__(format_spec) -> string
|
| Return a formatted version of S as described by format_spec.
|
| __ge__(...)
| x.__ge__(y) <==> x>=y
|
| __getattribute__(...)
-- More --
解决方案 6:
让我们直接回答你的问题。
正在寻找内置 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 代码。
解决方案 7:
Python开发者指南是一个非常不为人知的资源。
在最近的 GH问题中,添加了一个新章节来解决您提出的问题:CPython 源代码布局。如果发生任何变化,该资源也会更新。
解决方案 8:
正如@Jim所说,文件组织在此处描述。为方便发现而复制:
对于 Python 模块,典型的布局是:
Lib/<module>.py Modules/_<module>.c (if there’s also a C accelerator module) Lib/test/test_<module>.py Doc/library/<module>.rst
对于仅扩展模块,典型的布局是:
Modules/<module>module.c Lib/test/test_<module>.py Doc/library/<module>.rst
对于内置类型,典型的布局是:
Objects/<builtin>object.c Lib/test/test_<builtin>.py Doc/library/stdtypes.rst
对于内置函数,典型的布局是:
Python/bltinmodule.c Lib/test/test_builtin.py Doc/library/functions.rst
一些例外:
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
解决方案 9:
以下是从《CPython Internals Book》(撰写本书时为 Python 3.9)中引用的目录布局:
cpython
├── Doc Source for the documentation
├── Grammar The computer-readable language definition
├── Include The C header files
├── Lib Standard library modules written in Python
├── Mac macOS support files
├── Misc Miscellaneous files
├── Modules Standard library modules written in C
├── Objects Core types and the object model
├── Parser The Python parser source code
├── PC Windows build support files for older versions of Windows
├── PCbuild Windows build support files
├── Programs Source code for the ‘python’ executable and other binaries
├── Python The CPython interpreter source code
├── Tools Standalone tools useful for building or extending CPython
├── m4 Custom scripts to automate configuration of the makefile
*内置函数位于目录bltinmodule.c
内的文件中/Python
。