Debug With bpython
00:10 However, you can also import any of bpython’s internal modules into your regular scripts. Some of them may become particularly useful for debugging. Let’s say you wanted to perform postmortem debugging after intercepting an exception. In such a case, you can embed and start the bpython REPL right after your script after it crashes to introspect local variables using the dynamic nature of Python.
If the user provides a non-integer value for either of the two variables, then Python will raise a
ValueError. When both values entered by the user are valid integers, but the second one is equal to zero, then you’ll end up with a
Remember that you must run the script from a virtual environment with bpython installed. Otherwise, you won’t be able to import its modules. As soon as there’s an exception, you are dropped into an interactive bpython session with access to all your local variables including
y, which you can inspect and manipulate to gain additional insight into the issue.
Embedding a bpython REPL may not be enough. If you want to use a proper debugger to step through your code and manipulate the local variables at any point in the execution, then you can use the
bpdb debugger that comes with bpython.
It’s nearly identical to Python’s
pdb debugger, but has an additional
b command that starts bpython at the current stack frame. To take advantage of
bpdb, you can modify your existing
adder.py script as seen on-screen.
Note that since Python 3.7, you can tell the built-in
breakpoint() convenience function to have the same effect. Unfortunately, the function is hardwired to the classic
pdb debugger by default, so if you want to take advantage of
bpdb instead, then you should import it explicitly as in the example seen on-screen.
You can control which command
breakpoint() delegates by setting the
PYTHONBREAKPOINT environment variable. For example, if you set its value to
breakpoint() will always start the
can step through the code line by line. typing the lowercase letter
n and confirming with Enter advances to the next line. At any point, you can type the uppercase letter
B to embed the bpython REPL.
03:45 You can exit the debugger in the same way you typically exit the REPL—i.e., hit and Ctrl + D to send the end-of-file character. Naturally, bpython comes with many more useful modules that you can take advantage of for purposes other than debugging. For instance, you could leverage its excellent code introspection mechanism if you’re writing a static code analysis tool or something similar.
Become a Member to join the conversation.