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 by breakpoint()
.
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 list here.
h
or help
: Prints a list of available commands. If you give an argument, e.g. help continue
, prints help of the continue
command.l
or list
: List a piece of code around the current position.n
or next
: Execute next line.s
or step
: Same as next
but "steps into" the function called in the next line.c
or continue
: Continue execution until next breakpoint.r
or return
: Continue execution until the return of current function.q
or quit
: 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 the Pdb().set_trace()
(this is the Jupyter notebook equivalent for breakpoint()
) 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 between n
and s
.
from IPython.core.debugger import Pdb
class SuperGreeter:
def __init__(self, people_to_greet):
self.people = people_to_greet
def greet(self):
for person in self.people:
if person.islower():
self._greet_street_style(person)
elif len(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() # UNCOMMENT
name = name.upper()
print(f"WASSUP {name}!?")
def _greet_hawaii(self, name):
print(f"Aloha {name}!")
def main():
people = ["John Doe", "Donald", "Lisa", "alex"]
# Pdb().set_trace() # UNCOMMENT
greeter = SuperGreeter(people)
greeter.greet()
main()
Aloha John Doe! G'day Donald! How are you doing? G'day Lisa! How are you doing? WASSUP ALEX!?