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

Why can not we inspect the source code of the `__builtins__` module?

为什么我不能查看__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.

除了按照 here and there 所述浏览 Python GitHub 存储库之外,是否有 克服此问题的方法。

您只能通过这种方式检查 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 而不是抓取,并且您希望能够搜索本地存储库(如果找不到则可能克隆它) and/or 在运行之间缓存东西,等等,这显示了它是多么容易以及它需要多少特殊外壳。


因此,最好的选择是克隆存储库并手动查找内容,或者直接在 github.

上浏览