我尝试使用 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
源:
- https://github.com/python/cpython/blob/master/Objects/listobject.c (最新开发版)
- https://github.com/python/cpython/blob/3.6/Objects/listobject.c
- https://github.com/python/cpython/blob/2.7/Objects/listobject.c
...等等。
关于python - 为什么我不能使用 inspect.getsource() 查看列表的来源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23679412/