Question

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])
Was it helpful?

Solution

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.

  1. Download the Python source code found at https://www.python.org/downloads/

  2. Untar the Python source code | tar xzvf Python-2.7.6.tar.gz

  3. Enter the untarred directory and run the configuration script using | ./configure

  4. Compile with debug symbols | make -g

  5. Start your custom compiled debug Python with the GNU Debugger | gdb ./python

  6. Set a breakpoint in GDB for the sum() call | b bltinmodule.c:builtin_sum.

  7. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top