r/pythontips • • Mar 24 '21

Python3_Specific How to debug in Python?

Please share some tips about the title.

32 Upvotes

38 comments sorted by

View all comments

2

u/SpiderJerusalem42 Mar 25 '21 edited Mar 25 '21

Say you write some code, and you have the ability to debug in PyCharm. What you would do if you wanted to debug your program would be to set a break point by left clicking to the right of the line number you would like to set a break point. A break point will halt execution of the program before the execution of the line where the break point is set. From here, when you go to run your code, via the run menu (alt+'u'), Debug (Shift + F9) you might need to pick the program you want to debug with Alt+Shift+F9.

From here, you want to step through your code with the step commands and monitor the debugger window. More on the debugger window later. There are usually hot keys for moving through code execution. I think in the jetbrains suite, F8 steps over, F9 resumes, F7 steps into. To give you an idea what that means, steps over means that whole function call gets handled, and so long as it doesn't hit a breakpoint somewhere down the call stack, will move execution from the current line to the next one. Stepping into will attempt to go into the function implementation of any function calls you have made. If you make several calls on a single line, you might have to go into and out over several function calls before you get to the one you want to examine the functioning of.

The debugger window shows the value of various variables that have been defined in the running of your program. You can also set watches. You can use python expressions to define these watches, so you can take a part of a command that can be interpreted independently as an expression that has a value, and try to see why another expression didn't work out, while you were executing code. You can look at variables to make sure they are consistent with the logic in your head, as the code executes.

You can also right click on breakpoints and set a break condition. This is helpful if you hit a big loop, and don't want to step through to the condition you think is breaking.

I like to think of debugging as watching your code fail in a play by play, slow motion review.