查找内置Python函数的源代码?

use*_*865 114 python python-internals

有没有办法看到内置函数如何在python中工作?我不是指如何使用它们,而是它们是如何构建的,排序枚举背后的代码是什么......?

Chr*_*ris 111

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

要查找特定模块或函数在哪个文件中实现,通常可以打印该__file__属性.或者,您可以使用该inspect模块,请参阅文档中的检索源代码部分inspect.

对于内置的类和方法,这不是因为这么简单的inspect.getfileinspect.getsource会返回一个类型错误,指出对象是内置.但是,许多内置类型可以Objects在Python源中继子目录中找到.例如,请参阅此处了解枚举类的实现,或者在此处查看list类型的实现.

  • @Quetzalcoatl `sorted()` 的源代码在 [/Python/bltinmodule.c](https://github.com/python/cpython/blob/d246a6766b9d8cc625112906299c4cb019944300/Python/bltinmodule.c#L2237L)只是调用`list.sort()` 所以真正的来源在[/Objects/listobject.c](https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Objects/listobject.c#L2151-L2152) (4认同)
  • 作为对自己和未来 googlers 的注释:`open()` 函数是在 Python 3 的 `Modules/_io/_iomodule.c` 中定义的(而不是在其他内置函数中)。 (3认同)
  • 如果您给出了如何使用 ``__file__``` 的示例,将会很有帮助 (2认同)

kev*_*rpe 30

这是补充@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()

请享用.

  • `bltin 模块`。啊啊啊啊啊。为什么他们要把它拼写得这么糟糕?我尝试在文件系统中快速搜索“builtin”,但一无所获! (7认同)

tba*_*ack 17

IPython的外壳让一切变得简单:function?给你的文档.function??还显示了代码.但这仅适用于纯python函数.

然后你总是可以下载(c)Python的源代码.

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

  • 请参阅早期项目以查看内置函数的源代码:https://github.com/punchagan/cinspect (2认同)

use*_*754 14

在此输入图像描述

我不得不挖掘一点来找到以下的来源,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

  • 列表是一个对象/类型,而不是内置函数。您可以在 `listobject.c` https://github.com/python/cpython/tree/master/Objects 中找到其实现细节 (2认同)

Guz*_*ero 11

让我们直接回答你的问题。

寻找内置 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;
}
Run Code Online (Sandbox Code Playgroud)

您可能已经注意到,这不是 Python 代码,而是 C 代码。


Mat*_*haq 8

正如 @Jim 所提到的,文件组织在此处进行了描述。为了便于发现而转载:

\n\n
\n

对于 Python 模块,典型的布局是:

\n\n
Lib/<module>.py\nModules/_<module>.c (if there\xe2\x80\x99s also a C accelerator module)\nLib/test/test_<module>.py\nDoc/library/<module>.rst\n
Run Code Online (Sandbox Code Playgroud)\n\n

对于仅扩展模块,典型布局是:

\n\n
Modules/<module>module.c\nLib/test/test_<module>.py\nDoc/library/<module>.rst\n
Run Code Online (Sandbox Code Playgroud)\n\n

对于内置类型,典型的布局是:

\n\n
Objects/<builtin>object.c\nLib/test/test_<builtin>.py\nDoc/library/stdtypes.rst\n
Run Code Online (Sandbox Code Playgroud)\n\n

对于内置函数,典型的布局是:

\n\n
Python/bltinmodule.c\nLib/test/test_builtin.py\nDoc/library/functions.rst\n
Run Code Online (Sandbox Code Playgroud)\n\n

一些例外:

\n\n
builtin type int is at Objects/longobject.c\nbuiltin type str is at Objects/unicodeobject.c\nbuiltin module sys is at Python/sysmodule.c\nbuiltin module marshal is at Python/marshal.c\nWindows-only module winreg is at PC/winreg.c\n
Run Code Online (Sandbox Code Playgroud)\n
\n


Moh*_*med 7

2种方法

  1. 您可以使用查看有关代码段的用法 help()
  2. 您可以使用以下命令检查这些模块的隐藏代码 inspect

1)检查:

使用inpsect模块来浏览所需的代码... 注意:您只能浏览已导入的模块(aka)软件包的代码

例如:

  >>> import randint  
  >>> from inspect import getsource
  >>> getsource(randint) # here i am going to explore code for package called `randint`
Run Code Online (Sandbox Code Playgroud)

2)help():

您只需使用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  --
Run Code Online (Sandbox Code Playgroud)

  • OP 特别想查看代码,帮助仅提供文档。 (7认同)
  • 和检查不适用于内置功能。 (2认同)

Jim*_*ard 6

《 Python 开发人员指南》是很多未知资源。

在最近的GH 问题(有点)中,添加了新的章节来解决您要问的问题:CPython源代码布局。如果应该更改某些内容,该资源也将得到更新。