有没有一种方法可以看到python中内置函数是如何工作的?我的意思不仅仅是如何使用它们,还包括它们是如何构建的,排序或枚举等背后的代码是什么?
当前回答
这是一个食谱回答补充@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()
享受。
其他回答
这是一个食谱回答补充@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()
享受。
我不得不挖掘一点来找到以下内置函数的源代码,因为搜索会产生成千上万的结果。(祝你能找到任何一个来源)
不管怎样,所有这些函数都是在bltinmodule.c中定义的。
内置来源:https://github.com/python/cpython/blob/master/Python/bltinmodule.c 对于内置类型: https://github.com/python/cpython/tree/master/Objects
iPython shell让这变得很简单:function?会给你文件。函数? ?还显示了代码。但这只适用于纯python函数。
然后您可以随时下载(c)Python的源代码。
如果你对核心功能的python实现感兴趣,可以看看PyPy源代码。
2方法,
可以使用help()检查代码段的使用情况 您可以使用inspect检查这些模块的隐藏代码
1)检查:
使用检查模块来探索你想要的代码… 注意:你只能浏览你导入的模块(又名包)的代码
如:
>>> import randint
>>> from inspect import getsource
>>> getsource(randint) # here i am going to explore code for package called `randint`
2)帮助():
您可以简单地使用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 --
Python开发者指南是一个相当不为人知的资源。
在(有点)最近的GH问题中,添加了一个新的章节来解决您所问的问题:CPython源代码布局。如果某些内容发生更改,该资源也将得到更新。