有没有一种方法可以看到python中内置函数是如何工作的?我的意思不仅仅是如何使用它们,还包括它们是如何构建的,排序或枚举等背后的代码是什么?


当前回答

iPython shell让这变得很简单:function?会给你文件。函数? ?还显示了代码。但这只适用于纯python函数。

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

如果你对核心功能的python实现感兴趣,可以看看PyPy源代码。

其他回答

正如@Jim提到的,这里描述了文件组织。为便于发现而转载:

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

因为Python是开源的,你可以阅读源代码。

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

对于内置类和方法,这不是那么简单,因为inspect。获取文件并检查。Getsource将返回一个类型错误,说明该对象是内置的。然而,许多内置类型可以在Python源中继的Objects子目录中找到。例如,在这里可以看到枚举类的实现,在这里可以看到列表类型的实现。

iPython shell让这变得很简单:function?会给你文件。函数? ?还显示了代码。但这只适用于纯python函数。

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

如果你对核心功能的python实现感兴趣,可以看看PyPy源代码。

Python开发者指南是一个相当不为人知的资源。

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

这是一个食谱回答补充@Chris的回答,CPython已经转移到GitHub, Mercurial存储库将不再更新:

必要时安装Git。 Git克隆https://github.com/python/cpython.git 代码将检出到名为cpython -> cd cpython的子目录 假设我们正在寻找print()的定义… egrep——color=always -R 'print' | less -R 啊哈!参见Python/bltinmodule.c -> builtin_print()

享受。