为什么无法使用inspect.getsource()查看list的源代码?
我尝试使用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
我不明白为什么这没能成功——关于inspect.getsource()
的文档说:
如果无法获取源代码,将引发一个IOError。
...但没有解释为什么会发生这种情况(而且我得到的是TypeError
,而不是IOError
)。
有没有其他方法可以在这种情况下以编程方式获取对象的源代码?如果没有,我该如何自己找到源代码呢?
1 个回答
13
虽然 inspect.getsource()
可以获取用 Python 写的对象的源代码,但 list
是用 C 语言写的,所以 getsource()
找不到 Python 的源代码。
如果你能看懂 C 语言,可以在 Python 的 官方 GitHub 仓库 找到完整的源代码。例如,不同版本的 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
... 还有其他版本。