Home > Software design >  Import pprint for every breakpoint()
Import pprint for every breakpoint()

Time:05-26

Every time I use breakpoint() in python I inevitably end up importing pprint (from pprint import pprint). Is there a way to automatically add pprint to the namespace whenever breakpoint() is reached?

Python 3.8.5

Similar questions that don't quite solve this problem or predate the implementation of breakpoint()

CodePudding user response:

Make a file like this, put it into an installable package if you want, or just drop it somewhere on the PYTHONPATH:

$ cat mybreakpoint.py 
import pdb

def pprint_breakpoint():
    import pprint
    pdb.set_trace()

Now you can use the env var PYTHONBREAKPOINT to customize the debugger scope like that:

$ PYTHONBREAKPOINT=mybreakpoint.pprint_breakpoint python3
Python 3.11.0b1 (main, May 18 2022, 12:50:35) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> breakpoint()
--Return--
> .../mybreakpoint.py(5)pprint_breakpoint()->None
-> pdb.set_trace()
(Pdb) pprint.pprint({"k2":"v2", "k1":"v1"})
{'k1': 'v1', 'k2': 'v2'}

Personally, I always install IPython into my development environments, so that I can use PYTHONBREAKPOINT=IPython.embed and get a more full-featured REPL in breakpoints by default, including IPython's pretty printer.

  • Related