问题:查找内置Python函数的源代码?
有没有办法查看内置函数如何在python中工作?我不仅意味着如何使用它们,而且还意味着它们是如何构建的,排序或枚举后的代码是什么?
回答 0
由于Python是开源的,因此您可以阅读源代码。
要找出实现了特定模块或功能的文件,通常可以打印__file__属性。或者,您可以使用该inspect模块,请参阅的文档中的“ 检索源代码 ”部分inspect。
对于内置的类和方法,这是不是这样,因为直白inspect.getfile,并inspect.getsource会返回一个类型错误,指出对象是内置。但是,可以Objects在Python源trunk的子目录中找到许多内置类型。例如,看到这里的枚举类的实现或这里的执行list类型。
回答 1
这是一个补充@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()
请享用。
回答 2
我不得不花点时间找到以下内容的来源,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
回答 3
该IPython的外壳让一切变得简单:function?给你的文档。function??同时显示代码。但是这仅适用于纯python函数。
然后,您随时可以下载(c)Python的源代码。
如果您对核心功能的pythonic实现感兴趣,请查看PyPy源代码。
回答 4
2种方法
- 您可以使用查看有关代码段的用法 help()
- 您可以使用以下命令检查这些模块的隐藏代码 inspect
1)检查:
使用inpsect模块来浏览所需的代码… 注意:您只能浏览已导入的模块(aka)软件包的代码
例如:
  >>> 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  --
回答 5
《 Python 开发人员指南》是很多未知资源。
在最近的GH 问题(有点)中,增加了一个新章节来解决您所问的问题:CPython源代码布局。如果应该更改某些内容,该资源也将得到更新。
回答 6
如@Jim所述,此处描述了文件组织。为便于发现而复制:
对于Python模块,典型的布局为:
Lib/<module>.py Modules/_<module>.c (if there’s also a C accelerator module) Lib/test/test_<module>.py Doc/library/<module>.rst对于仅扩展模块,典型布局为:
Modules/<module>module.c Lib/test/test_<module>.py Doc/library/<module>.rst对于内置类型,典型的布局为:
Objects/<builtin>object.c Lib/test/test_<builtin>.py Doc/library/stdtypes.rst对于内置函数,典型布局为:
Python/bltinmodule.c Lib/test/test_builtin.py Doc/library/functions.rst一些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


