【问题标题】:Why can't I use inspect.getsource() to view the source for list?为什么我不能使用 inspect.getsource() 查看列表的来源?
【发布时间】:2014-05-15 13:16:55
【问题描述】:

我尝试使用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() 这么说

如果无法检索源代码,则会引发 IOError。

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

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

【问题讨论】:

标签: python list introspection python-internals


【解决方案1】:

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

如果您喜欢阅读 C,您可以在其official GitHub repo 找到 Python 的完整源代码。例如,各种版本的list 的来源可以在以下位置找到:

...等等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-05
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2023-03-24
    • 2021-11-19
    • 1970-01-01
    相关资源
    最近更新 更多