有没有办法查看内置函数在 python 中是如何工作的?我的意思不仅仅是如何使用它们,还包括它们是如何构建的,排序或枚举背后的代码是什么......?
8 回答
由于 Python 是开源的,您可以阅读源代码。
要找出特定模块或功能在哪个文件中实现,您通常可以打印__file__
属性。或者,您可以使用该inspect
模块,请参阅.inspect
对于内置的类和方法,这不是那么简单,因为inspect.getfile
并且inspect.getsource
会返回一个类型错误,说明该对象是内置的。但是,许多内置类型可以在Objects
Python 源 trunk 的子目录中找到。例如,请参见此处了解枚举类的实现或此处了解list
类型的实现。
这是补充@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()
享受。
I had to dig a little to find the source of the following Built-in Functions
as the search would yield thousands of results. (Good luck searching for any of those to find where it's source is)
Anyway, all those functions are defined in bltinmodule.c
Functions start with builtin_{functionname}
Built-in Source: https://github.com/python/cpython/blob/master/Python/bltinmodule.c
For Built-in Types: https://github.com/python/cpython/tree/master/Objects
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)帮助():
you can simply use help()
command to get help about builtin functions as well its code.
for eg:
if you want to see the code for str() , simply type - help(str)
it will return like this,
>>> 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 --
Quite an unknown resource is the Python Developer Guide.
In a (somewhat) recent GH issue, a new chapter was added for to address the question you're asking: CPython Source Code Layout. If something should change, that resource will also get updated.
Let's go straight to your question.
Finding the source code for built-in Python functions?
The source code is located at cpython/Python/bltinmodule.c
To find the source code in the GitHub repository go here. You can see that all in-built functions start with builtin_<name_of_function>
, for instance, sorted()
is implemented in builtin_sorted
.
For your pleasure I'll post the implementation of 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;
}
As you may have noticed, that's not Python code, but C code.
As mentioned by @Jim, the file organization is described here. Reproduced for ease of discovery:
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