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

有没有办法查看内置函数如何在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…?


回答 0

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

要找出实现了特定模块或功能的文件,通常可以打印__file__属性。或者,您可以使用该inspect模块,请参阅的文档中的“ 检索源代码 ”部分inspect

对于内置的类和方法,这是不是这样,因为直白inspect.getfile,并inspect.getsource会返回一个类型错误,指出对象是内置。但是,可以Objects在Python源trunk子目录中找到许多内置类型。例如,看到这里的枚举类的实现或这里的执行list类型。

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.


回答 1

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

请享用。

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.


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

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


回答 3

IPython的外壳让一切变得简单: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.


回答 4

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`

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

回答 5

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


回答 6

如@Jim所述,此处描述了文件组织。为便于发现而复制:

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

Lib/<module>.py
Modules/_<module>.c (if theres 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

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。