How can I see the source code of the built-in functions?

I tried to connect the inspect module and, calling the getsource function, set the required function as a parameter. But the method of the specified module refused to return the source code for the built-in functions, but, for example, if you feed the getsource function to the print function, then there will be no error and I will be able to get what I wanted.

  • 2
    they are built-in functions. print has also been a built-in operator function for a long time (I cannot vouch for precise definition). In most of these functions, the source code is not on python, but somewhere deep in c / c ++ code. - KoVadim
  • @KoVadim: print not a function in Python 2 (without __future__ ). print() in Python 3 is a function (built-in function in CPython - both in the sense that it is not implemented on pure Python, or in the __builtins__ namespace). - jfs
  • I know that print was not a function - I wrote about it. But then they decided to make it. - KoVadim

2 answers 2

As KoVadim wrote, many of the built-in functions of python are written in C. But, since Python is an open source language, the source can be viewed here . If the implementation of the same modules on python is interesting, then I advise you to look at the PyPy sources .

PS To find out which file belongs to which module, you can usually look at the __file__ property.

PPS There is a similar question on the English stack.

    The phrase "built-in function" in the error message means that the corresponding function is not implemented on pure Python:

     >>> import inspect >>> import numpy >>> inspect.getsource(print) Traceback (most recent call last): ... TypeError: <built-in function print> is not a module, class, method, function, traceback, frame, or code object >>> inspect.getsource(numpy.array) Traceback (most recent call last): ... TypeError: <built-in function array> is not a module, class, method, function, traceback, frame, or code object 

    Obviously, numpy.array not a "built-in function" in the sense of belonging to the __builtins__ namespace , but is a "built-in function" in the sense of "not implemented on pure Python".

    The source code of such functions should be found in the relevant projects: CPython's print() , Pypy , Jython's print() , numpy.array() , numpy for Pypy .