How can I examine the code of a python built-in function, for example step into sum()
?
https://docs.python.org/2/library/functions.html#sum.
I expected to see what sum()
does using the code below and s
command in pdb:
import pdb
def adder(nums):
x = sum(nums)
return x
pdb.set_trace()
print adder([1, 2, 3,4])
Some of the Python modules are written in C (to increase performance) and cannot be stepped through in pdb
. If you really want to see what's going on in these functions it's possible, but not trivial. To examine C functions I typically use the GNU Debugger (GDB) and compile Python with debugging symbols enabled.
Download the Python source code found at https://www.python.org/downloads/
Untar the Python source code | tar xzvf Python-2.7.6.tar.gz
Enter the untarred directory and run the configuration script using | ./configure
Compile with debug symbols | make -g
Start your custom compiled debug Python with the GNU Debugger | gdb ./python
Set a breakpoint in GDB for the sum()
call | b bltinmodule.c:builtin_sum
.
Run your script from GDB (I called mine sumtest.py) | run ~/sumtest.py
The first thing that happens is you get prompted for your PDB call. Continue using c
.
The next break is in the middle of the sum function in C. You can use info locals
to list all the local variables. Just like in PDB c
is used to continue execution to the next breakpoint amd s
is used to step through single instructions.