有没有一种方法可以看到python中内置函数是如何工作的?我的意思不仅仅是如何使用它们,还包括它们是如何构建的,排序或枚举等背后的代码是什么?
当前回答
Python开发者指南是一个相当不为人知的资源。
在(有点)最近的GH问题中,添加了一个新的章节来解决您所问的问题:CPython源代码布局。如果某些内容发生更改,该资源也将得到更新。
其他回答
正如@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开发者指南是一个相当不为人知的资源。
在(有点)最近的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()
享受。
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 --
iPython shell让这变得很简单:function?会给你文件。函数? ?还显示了代码。但这只适用于纯python函数。
然后您可以随时下载(c)Python的源代码。
如果你对核心功能的python实现感兴趣,可以看看PyPy源代码。