pdb
¶Your program does not always behave how you would expect it to behave. If the origin of the mistake is unclear, debugging is usually the most effective to find the root cause of the unexpected behavior. The Python Standard Library has a built-in debugger which is a powerful tool for solving any issues related to your code.
breakpoint()
¶The basic use case for debugging is that you want to stop the execution of your program at some certain point and monitor variable values or program execution in general from that specific point onward. You stop the execution at the point you want by setting a breakpoint into code bybreakpoint()
.
When you execute your program, the execution will stop at this point and will enter to interactive debugger session. You can add as many breakpoints into your code as you want.
See the full listhere.
h
orhelp
: Prints a list of available commands. If you give an argument, e.g.help continue
, prints help of thecontinue
command.l
orlist
: List a piece of code around the current position.n
ornext
: Execute next line.s
orstep
: Same asnext
but "steps into" the function called in the next line.c
orcontinue
: Continue execution until next breakpoint.r
orreturn
: Continue execution until the return of current function.q
orquit
: Quit debugger and abort program execution.Note that you can see the value of any variable by typing the variable name during the debugging session. You can also execute arbitrary code during the debugging session.
Uncomment thePdb().set_trace()
(this is the Jupyter notebook equivalent forbreakpoint()
) lines and execute the cell. Execute the program line by line by using the commands defined above. Try all the above mentioned commands at least once. Pay attention to the difference betweenn
ands
.
fromIPython.core.debuggerimportPdbclassSuperGreeter:def__init__(self,people_to_greet):self.people=people_to_greetdefgreet(self):forpersoninself.people:ifperson.islower():self._greet_street_style(person)eliflen(person)>7:self._greet_hawaii(person)else:self._greet_polite(person)def_greet_polite(self,name):greeting=f"G'day{name}! How are you doing?"print(greeting)def_greet_street_style(self,name):# Pdb().set_trace() # UNCOMMENTname=name.upper()print(f"WASSUP{name}!?")def_greet_hawaii(self,name):print(f"Aloha{name}!")defmain():people=["John Doe","Donald","Lisa","alex"]# Pdb().set_trace() # UNCOMMENTgreeter=SuperGreeter(people)greeter.greet()main()
Aloha John Doe!G'day Donald! How are you doing?G'day Lisa! How are you doing?WASSUP ALEX!?