Skip to Content

Context Managers for Debugging

A small helper I use to debug some python programs:

from contextlib import contextmanager

@contextmanager
def debug_error():
    try:
        yield
    except Exception as e:
        breakpoint()
        quit()

### usage

with debug_error():
  x = 1
  y = 0
  x/y # x and y will be avail in pdb

You can also put things before the yield (which will run before the with block), and after it (to run at the end of the block.) Anything put after it will run at the end of the block. See @contextmanager for more info.

Notes

  • This is most handy when debugging an extension to something, like a directive for Sphinx or a lexer for pygments. Otherwise you could use an inline debugger or call python with -m pdb file, which automatically starts pdb on an uncaught error.
  • I should probably make a library of useful debugging tools for easy import into projects.
  • Context managers seem like a really useful tool? Seem like something designed for library programmers that’d also help application programmers. The contextlib package also has some neat stuff like suppress.