193

有没有办法查看内置函数在 python 中是如何工作的?我的意思不仅仅是如何使用它们,还包括它们是如何构建的,排序枚举背后的代码是什么......?

4

8 回答 8

183

由于 Python 是开源的,您可以阅读源代码

要找出特定模块或功能在哪个文件中实现,您通常可以打印__file__属性。或者,您可以使用该inspect模块,请参阅.inspect

对于内置的类和方法,这不是那么简单,因为inspect.getfile并且inspect.getsource会返回一个类型错误,说明该对象是内置的。但是,许多内置类型可以在ObjectsPython 源 trunk 的子目录中找到。例如,请参见此处了解枚举类的实现或此处了解list类型的实现。

于 2011-12-22T19:06:01.147 回答
42

这是补充@Chris 答案的食谱答案,CPython 已移至 GitHub,Mercurial 存储库将不再更新:

  1. 必要时安装 Git。
  2. git clone https://github.com/python/cpython.git

  3. 代码将检出到名为cpython->的子目录cd cpython

  4. 假设我们正在寻找print()...的定义
  5. egrep --color=always -R 'print' | less -R
  6. 啊哈!见Python/bltinmodule.c->builtin_print()

享受。

于 2014-11-15T14:56:36.803 回答
32

enter image description here

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

于 2017-11-18T21:36:09.400 回答
22

iPython shell 使这变得简单:将为function?您提供文档。function??还显示了代码。但这仅适用于纯 python 函数。

然后您可以随时下载(c)Python 的源代码。

如果您对核心功能的 pythonic 实现感兴趣,请查看PyPy源代码。

于 2011-12-22T19:10:35.803 回答
12

2种方法,

  1. 您可以使用help()
  2. 您可以使用检查这些模块的隐藏代码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  --
于 2016-12-09T14:09:12.850 回答
8

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.

于 2018-01-06T09:56:00.480 回答
8

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.

于 2020-11-16T23:18:51.903 回答
4

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
于 2019-07-29T06:28:51.360 回答