Search code examples
pythonpython-3.xpython-internals

Why does inspect.getsource throw TypeError when trying to get source for Python Built-in?


What is the difference between a python built-in and a normal object? we often say that in python everything is an object. for example, when I do this in Python 3.6:

>>> import os, inspect
>>> inspect.getsource(os.scandir)
TypeError: <built-in function scandir> is not a module, class, method, function, traceback, frame, or code object

I have two questions:

  1. is built-in function an object? if not is this why getsource throws TypeError?
  2. why can't I find scandir in python3 documentation as a built-in?

Solution

  • You can't access the source of builtins and other modules that were written using the C API, since there isn't a Python source for them.

    From the documentation for inspect.getsourcefile(object):

    Return the name of the Python source file in which an object was defined. This will fail with a TypeError if the object is a built-in module, class, or function.