A debugger is tools that helps you to solve problems that are not understood in your scripts.

It allows you to execute a program step by step, to study the execution of the code in real-time and to see the value of the variables at a precise place.

You can debug your script as you wish; often a print is enough but in more complex cases you can use more advanced tool such as ipdb which is a combination of ipython and pdb

# 📥 Installing ipdb#

Let’s go through pip :

pip install ipdb


# 🐞 Implement ipdb in your program#

You just need to add the following line at the place where you want to debug your code:

import ipdb; ipdb.set_trace()


# 💡 Exemple#

Let’s add set_trace to our code like this:

class LoginView():

template_name = 'front/index.html'

def post(self, request, **kwargs):

import ipdb; ipdb.set_trace()



Then let’s run our code (in our case it is a Django script)

We see that the script has stopped and this is displayed in our console:

----> 9                 username = request.get('username', False)

ipdb>


At this point you can do whatever you want to do. for instance:

• look/change variables values

ipdb> self.template_name = "front/error.html"
ipdb> print(self.template_name)
"front/error.html"

• n $\rightarrow$ execute the current line and move to the next line

ipdb> n
11

ipdb>

• q $\rightarrow$ quit wildly

• c $\rightarrow$ continue the execution of the program until its end

• s $\rightarrow$ enter the function of the current line

• r $\rightarrow$ execute a return

# 🤌 My usage#

This is one of the most powerful to that I discover in python (for real). I see lot of people placing many print then running and after seeing that there is nothing wrong with what they print they print another variable. with ipdb the code stop and you can watch whatever you want then continue the running.

In ML model I use it with pytorch in forward methods to reorganize my matrix multiplication when I am confused. Sometime I put it in try catch like this example:

try:
# code
except:
import ipdb; ipdb.set_trace()