python - 为什么我不能使用 inspect.getsource() 查看列表的来源?

标签 python list introspection python-internals

我尝试使用 inspect 检索 list 类的源代码模块,没有成功:

>>> import inspect
>>> inspect.getsource(list)
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 408, in getfile
    raise TypeError('{!r} is a built-in class'.format(object))
TypeError: <module '__builtin__' (built-in)> is a built-in class

我不明白为什么这不起作用 - the documentation for inspect.getsource()说是

An IOError is raised if the source code cannot be retrieved.

...但没有解释为什么会发生这种情况(无论如何我得到的是 TypeError,而不是 IOError)。

在这种情况下,是否有其他方法可以通过编程方式检索对象的源代码?如果没有,我如何找到自己的来源?

最佳答案

同时 inspect.getsource()可以检索用 Python 编写的对象的源代码,list 是用 C 编写的,因此没有可供 getsource() 检索的 Python 源代码。

如果您熟悉 C 语言,可以在 official GitHub repo 找到 Python 的完整源代码。 .例如,可以在以下位置找到各种版本的 list 源:

...等等。

关于python - 为什么我不能使用 inspect.getsource() 查看列表的来源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23679412/

相关文章:

python - 将单个元素的列表或numpy数组转换为python中的 float

从列表 json.decoder.JSONDecodeError : Expecting value: line 1 column 1 (char 0) 循环时出现 python 错误

python - 如何查看 Python 对象内部?

python - 状态检查始终显示用户是 'offline'

python - 什么时候应该使用 setUpClass 什么时候只使用类成员?

java - 为整数列表创建特定模式

java - java中的反射或内省(introspection)有多昂贵

python - 如何实现 "if-else"条件,其中涉及在多列上乘以数字

Python flask 服务器需要很长时间才能启动

objective-c - 如何在 Objective-C 中列出对象的所有字段?