Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Import pprint for every breakpoint()

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading