Debugging in Python

Python has a simple yet powerful builtin module for debugging called pdb. Using this module you can debug your python code easily even without any IDE.

1. First step is to import the pdb module

2. Next step is to mark the entry point where the debugger would be called in. We use the set_trace() method for that.

3. When the program is run the execution would stop at the set_trace() method and would wait for debugging commands.

4. To run the next statment enter ‘n’ or ‘next’

5. To print a variable enter ‘pp variable_name’

6. To run until exit enter ‘c’ or ‘continue’

7. To display the current location enter ‘l’ or ‘list’
This would display an appropiate part of the source code with a pointer to the current statement.

8. To step into a method enter ‘s’ or ‘step’ when debugger is met with a method

9. To insert a break point enter ‘b filename:linenumber’

10. You can also dynamically assign values into variables.
Let’s assume there is a variable called num initialized to 10. You want to see what would happen when that variable is initialized to 20. You just do this. (pdb) num = 20 and then enter ‘n’ to execute next statement or enter ‘c’ to execute program until the end.

An example would look like this

import pdb

def method():
i = 10
name = ‘kasun’
last_letter = name[-1]

last_num = ord(last_letter)

print ‘last_num is’, last_num
if __name__ == ‘__main__’:


One response to “Debugging in Python

  1. looks cool. should try some time.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s