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:
- Install Git if necessary.
git clone https://github.com/python/cpython.git
Code will checkout to a subdirectory called
cpython
->cd cpython
- Let's say we are looking for the definition of
print()
... egrep --color=always -R 'print' | less -R
- Aha! See
Python/bltinmodule.c
->builtin_print()
Enjoy.
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
The iPython shell makes this easy: function?
will give you the documentation. function??
shows also the code. BUT this only works for pure python functions.
Then you can always download the source code for the (c)Python.
If you're interested in pythonic implementations of core functionality have a look at PyPy source.