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

发布于 2024-12-22 07:52:03 字数 127 浏览 1 评论 0原文

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

Is there a way to see how built in functions work in python? I don't mean just how to use them, but also how were they built, what is the code behind sorted or enumerate etc...?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

这样的小城市 2024-12-29 07:52:03

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

要找出特定模块或函数在哪个文件中实现,通常可以打印 __file__ 属性。或者,您可以使用 inspect 模块,请参阅 inspect 文档中的“noreferrer">检索源代码

对于内置类和方法来说,这并不是那么简单,因为 inspect.getfileinspect.getsource 将返回一个类型错误,表明该对象是内置的。但是,许多内置类型可以在 对象 Python 源码主干的子目录。例如,请参阅此处了解枚举类的实现或此处用于列表 类型。

Since Python is open source you can read the source code.

To find out what file a particular module or function is implemented in you can usually print the __file__ attribute. Alternatively, you may use the inspect module, see the section Retrieving Source Code in the documentation of inspect.

For built-in classes and methods this is not so straightforward since inspect.getfile and inspect.getsource will return a type error stating that the object is built-in. However, many of the built-in types can be found in the Objects sub-directory of the Python source trunk. For example, see here for the implementation of the enumerate class or here for the implementation of the list type.

愛上了 2024-12-29 07:52:03

输入图像描述这里

我必须深入挖掘才能找到以下内置函数的来源,因为搜索会产生数千个结果。 (祝你好运,搜索其中任何一个以找到其源代码)

无论如何,所有这些函数都在 bltinmodule.c 中定义,函数以 builtin_{functionname} 开头

内置源代码:https://github.com/python /cpython/blob/master/Python/bltinmodule.c

对于内置类型:
https://github.com/python/cpython/tree/master/Objects

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

等数载,海棠开 2024-12-29 07:52:03

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

  1. 如果需要的话安装Git。
  2. git 克隆 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()

享受吧。

Here is a cookbook answer to supplement @Chris' answer, CPython has moved to GitHub and the Mercurial repository will no longer be updated:

  1. Install Git if necessary.
  2. git clone https://github.com/python/cpython.git

  3. Code will checkout to a subdirectory called cpython -> cd cpython

  4. Let's say we are looking for the definition of print()...
  5. egrep --color=always -R 'print' | less -R
  6. Aha! See Python/bltinmodule.c -> builtin_print()

Enjoy.

莫多说 2024-12-29 07:52:03

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

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

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

The iPython shell makes this easy: function? will give you the documentation. function?? shows also the code. BUT this only works for pure python functions.

Then you can always download the source code for the (c)Python.

If you're interested in pythonic implementations of core functionality have a look at PyPy source.

土豪我们做朋友吧 2024-12-29 07:52:03

2 种方法,

  1. 您可以使用 help() 检查有关代码段的使用情况,
  2. 您可以使用 inspect 检查这些模块的隐藏代码

1) inform:

use < strong>inpsect 模块来探索您想要的代码...
注意:您只能浏览已导入的模块(又称)包的代码,

例如:

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

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  --

2 methods,

  1. You can check usage about snippet using help()
  2. you can check hidden code for those modules using inspect

1) inspect:

use inpsect module to explore code you want...
NOTE: you can able to explore code only for modules (aka) packages you have imported

for eg:

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

2) help():

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  --
記憶穿過時間隧道 2024-12-29 07:52:03

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

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

源代码位于 cpython/Python/bltinmodule.c

要在 GitHub 存储库中查找源代码,请转至 此处。您可以看到所有内置函数都以 builtin_ 开头,例如 sorted() 是在 builtin_sorted 中实现的。

为了让您高兴,我将发布 实现 < code>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代码。

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.

旧时光的容颜 2024-12-29 07:52:03

Python开发人员指南是一个相当未知的资源。

在(某种程度上)最近的 GH 问题 中,添加了一个新章节来解决该问题你问的是:CPython 源代码布局。如果发生变化,该资源也会更新。

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.

迷迭香的记忆 2024-12-29 07:52:03

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

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

Lib/<模块>.py
Modules/_.c(如果还有 C 加速器模块)
Lib/test/test_<模块>.py
文档/库/<模块>.rst

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

模块/<模块>module.c
Lib/test/test_<模块>.py
文档/库/<模块>.rst

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

Objects/object.c
Lib/test/test_.py
文档/库/stdtypes.rst

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

Python/bltinmodule.c
库/测试/test_builtin.py
文档/库/functions.rst

一些例外:

内置类型 int 位于 Objects/longobject.c
内置类型 str 位于 Objects/unicodeobject.c
内置模块 sys 位于 Python/sysmodule.c
内置模块 marshal 位于 Python/marshal.c
仅适用于 Windows 的模块 winreg 位于 PC/winreg.c

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
不再见 2024-12-29 07:52:03

以下是引用自《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 目录中。

Here is the directory layout quoted from the "CPython Internals Book"(Python 3.9 at the time of writing the book):

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

* the builtin functions are inside the bltinmodule.c file inside the /Python directory.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文