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
ipdb which is a combination of
📥 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()
set_trace to our code like this:
class LoginView(): template_name = 'front/index.html' def post(self, request, **kwargs): import ipdb; ipdb.set_trace() username = request.get('username', False) password = request.get('password', False) return (username, password)
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) 10 password = request.get('password', 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 9 username = request.get('username', False) ---> 10 password = request.get('password', False) 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
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()