Why can't I use inspect.getsource() to view the source for list?

introspection, list, python, python-internals

Solution

While `inspect.getsource()` can retrieve the source code for objects written in Python, `list` is written in C, so there's no Python source for `getsource()` to retrieve.

If you're comfortable reading C, you can find the complete source code for Python at its official GitHub repo. For example, the source of `list` for various releases can be found at:

- https://github.com/python/cpython/blob/master/Objects/listobject.c (latest development version)

- https://github.com/python/cpython/blob/3.6/Objects/listobject.c

- https://github.com/python/cpython/blob/2.7/Objects/listobject.c

... and so on.

Problem

I tried to retrieve the source code for the `list` class using the `inspect` module, without success: ``` >>> 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 ``` I don't understand why this didn't work - the documentation for `inspect.getsource()` says that An IOError is raised if the source code cannot be retrieved. ... but doesn't explain why that might happen (and in any case I got a `TypeError`, not an `IOError`). Is there some other way I can programmatically retrieve the source for an object in cases like this? If not, how can I find the source for myself?

Original source