Python Forum

Full Version: Python Debugger Suggestions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
https://python-forum.io/Thread-MySql-Cur...7#pid61337

tbh I highly dislike that the most common way to debug an application is to print variables out. Does anyone use a debugger? Perhaps with breakpoints, variable inspections, the ability to modify variables from a breakpoint and continue with the new values, etc?
What about pdb? I haven't tried it, but it comes with Python.
Ok, that's actually pretty good, but super hard to figure out how to use. Let's start with a broken file to test:
def fails(test: int = 7) -> str:
    x = 42
    assert x == test


if __name__ == '__main__':
    print(fails())
Proof that it's broken:
>python spam.py
Traceback (most recent call last):
  File "spam.py", line 7, in <module>
    print(fails())
  File "spam.py", line 3, in fails
    assert x == test
AssertionError
Debug (run until error, set a breakpoint, check values at that breakpoint, and set a local variable to fix issue, then continue running):
E:\Projects\etc>python -m pdb spam.py
> e:\projects\etc\spam.py(1)<module>()
-> def fails(test: int = 7) -> str:
(Pdb) continue
Traceback (most recent call last):
  File "E:\ProgramFiles\Python37\lib\pdb.py", line 1697, in main
    pdb._runscript(mainpyfile)
  File "E:\ProgramFiles\Python37\lib\pdb.py", line 1566, in _runscript
    self.run(statement)
  File "E:\ProgramFiles\Python37\lib\bdb.py", line 585, in run
    exec(cmd, globals, locals)
  File "<string>", line 1, in <module>
  File "e:\projects\etc\spam.py", line 1, in <module>
    def fails(test: int = 7) -> str:
  File "e:\projects\etc\spam.py", line 3, in fails
    assert x == test
AssertionError
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> e:\projects\etc\spam.py(3)fails()
-> assert x == test
(Pdb) list
  1     def fails(test: int = 7) -> str:
  2         x = 42
  3  ->     assert x == test
  4
  5
  6     if __name__ == '__main__':
  7         print(fails())
[EOF]
(Pdb) break 2
Breakpoint 1 at e:\projects\etc\spam.py:2
(Pdb) continue
Post mortem debugger finished. The spam.py will be restarted
> e:\projects\etc\spam.py(1)<module>()
-> def fails(test: int = 7) -> str:
(Pdb) continue
> e:\projects\etc\spam.py(2)fails()
-> x = 42
(Pdb) p x
*** NameError: name 'x' is not defined
(Pdb) p test
7
(Pdb) !test = 42
(Pdb) p test
42
(Pdb) continue
None
The program finished and will be restarted
> e:\projects\etc\spam.py(1)<module>()
-> def fails(test: int = 7) -> str:
(Pdb) exit
So it definitely works, but is loaded with magic incantations to work right. Maybe that's because I'm not used to command-line debuggers lol.
Now you know about the debugger, it's just a matter of using it.

Before you know it, you'll be writing tests, too.