Skip to content

Debugging with pdb

Allan Nordhøy edited this page Apr 18, 2018 · 4 revisions

Run pootle

To use pdb you will need to run Pootle in the foreground:

pootle runserver

You can also use pdb in tests or commands, or any other code that runs from the console.

Add a breakpoint

You can add a breakpoint anywhere in Python code

def some_function():
    do_something()
    import pdb; pdb.set_trace()
    do_something_else()

When this code is run the python interpreter will stop whenever it reaches this line of code, and allow you to interact with the program from the console where Pootle is being run.

If you are expecting the code to be triggered from a view, open the corresponding web page, and then switch back to your console.

Basic commands

  • l: list the lines of code surrounding the breakpoint (you can use eg l 20 to view lines around line 20)
  • n: execute the next line of code (or "step over")
  • c: continue program execution
  • s: "step into" the next line of code
  • q: quit the breakpoint

in most cases ctrl-c will execute the program altogether

Finding the calling code

You can find what code called a particularly method or function using inspect

When doing this inside pdb - you need to move up the stack beyond the pdb code

import inspect
inspect.stack()[10]

Avoid breaking in loops, or do so conditionally

Adding pdb inside a loop can cause the program to break repeatedly, often not when you actually wanted it to do so.

You can place the break before the loop, if you don't need to inspect variables inside it.

Alternatively add a condition to ensure that pdb is only activated at the point you need to introspect.

Breaking and continuing

Often you break at a certain point in the code and then realise you need to introspect at some point later in the program execution, but don't want to have to step over/into the code in between.

In this case you can set a further break point with eg b 23 where a breakpoint would be added at line 23. You can then use c to continue program execution, and you should reach your new breakpoint

Dont use in production!

pdb causes program execution to halt - this is not what you want in production!

Add commit hooks to prevent pdb being added and/or lint code to ensure it cannot ever reach production.

Clone this wiki locally