gpt4 book ai didi

python - 为什么不能查看 `__builtins__`模块的源码?

转载 作者:行者123 更新时间:2023-12-01 22:08:27 25 4
gpt4 key购买 nike

为什么我不能查看__builtins__的源代码模块?

>>> import inspect
>>> inspect.getsource(__builtins__)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/inspect.py", line 701, in getsource
lines, lnum = getsourcelines(object)
File "/usr/lib/python2.7/inspect.py", line 690, in getsourcelines
lines, lnum = findsource(object)
File "/usr/lib/python2.7/inspect.py", line 526, in findsource
file = getfile(object)
File "/usr/lib/python2.7/inspect.py", line 403, in getfile
raise TypeError('{!r} is a built-in module'.format(object))
TypeError: <module '__builtin__' (built-in)> is a built-in module

我经历了this谈话,但没有帮助。

如果我解释得好,这不应该发生:

>>> help(inspect.getsource)
Help on function getsource in module inspect:

getsource(object)
Return the text of the source code for an object.

The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a single string. An
IOError is raised if the source code cannot be retrieved.

有什么方法可以克服这个问题,而不是按照描述浏览 Python GitHub 存储库 herethere .

最佳答案

您只能通过这种方式检查 Python 源代码。使用 C API 编写的内置模块和扩展模块没有任何源代码,因此无法检查它。 (当你编译 C 代码时,结果可能有一些调试信息,包括用于构建它的文件的本地路径名,但它不包括实际的源文本。)

请注意,在您在文档中链接的函数的正上方,getsourcefile 说:

This will fail with a TypeError if the object is a built-in module, class, or function.

而且,正如您可能猜到的(或者可以通过查看从文档链接的 inspect.py 来验证),getsource 使用 getsourcefile 引擎盖下。


如果你在你的机器上本地构建 Python,并在构建后将源代码留在那里,有一个项目可以找到用于构建每个模块的 C 源代码,但我找不到它(我认为它在一个现在已经死了很久的 Berlios 或 Sourceforge),而且我认为它在 2.4 天左右之后没有更新过。

编写您自己的模块以在 github 存储库中查找源代码可能不会太难——或者,也许更好,在您自己的 github 存储库的本地克隆中。 (这比依赖本地构建的 Python 要好得多……)您甚至可以扩展它以使用 setuptools 信息来查找 pip 安装的扩展模块的源代码遵循某些常见的模式。但是,据我所知,还没有人发布过这样的模块。

如果您想自己构建类似的东西,请参阅 this quick&dirty proof of concept .尽管您可能想使用 git 或 Github API 而不是抓取,并且您希望能够搜索本地存储库(如果找不到,可能会克隆它)和/或缓存运行之间的事情,等等,这表明它是多么容易以及它需要多少特殊外壳。


因此,最好的选择是克隆 repo 并手动查找内容,或者直接在 github 上浏览。

关于python - 为什么不能查看 `__builtins__`模块的源码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50055640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com