Finding the source code for built-in Python functions? Finding the source code for built-in Python functions? python python

Finding the source code for built-in Python functions?


Since Python is open source you can read the source code.

To find out what file a particular module or function is implemented in you can usually print the __file__ attribute. Alternatively, you may use the inspect module, see the section Retrieving Source Code in the documentation of inspect.

For built-in classes and methods this is not so straightforward since inspect.getfile and inspect.getsource will return a type error stating that the object is built-in. However, many of the built-in types can be found in the Objects sub-directory of the Python source trunk. For example, see here for the implementation of the enumerate class or here for the implementation of the list type.


Here is a cookbook answer to supplement @Chris' answer, CPython has moved to GitHub and the Mercurial repository will no longer be updated:

  1. Install Git if necessary.
  2. git clone https://github.com/python/cpython.git

  3. Code will checkout to a subdirectory called cpython -> cd cpython

  4. Let's say we are looking for the definition of print()...
  5. egrep --color=always -R 'print' | less -R
  6. Aha! See Python/bltinmodule.c -> builtin_print()

Enjoy.


enter image description here

I had to dig a little to find the source of the following Built-in Functions as the search would yield thousands of results. (Good luck searching for any of those to find where it's source is)

Anyway, all those functions are defined in bltinmodule.c Functions start with builtin_{functionname}

Built-in Source: https://github.com/python/cpython/blob/master/Python/bltinmodule.c

For Built-in Types:https://github.com/python/cpython/tree/master/Objects