编程语言
首页 > 编程语言> > python – 为什么我不能使用inspect.getsource()来查看列表的来源?

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

作者:互联网

我试图使用inspect模块检索列表类的源代码,但没有成功:

>>> 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的完整源代码.例如,可以在以下位置找到各种版本的列表来源:

> 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,list,introspection,python-internals
来源: https://codeday.me/bug/20190722/1506827.html