Specialized tools are helpful, but it's the pretty print module that I go for when I need to debug a value in Python. I use a Visual Code (VS Code) snippet to load it quickly.
Here is the snippet I've used more than any other over the past few years:
"Pretty print": {
"scope": "python",
"prefix": "pp",
"body": [
"import pprint # isort: skip",
"pp = pprint.PrettyPrinter(indent=2)",
"print('-' * 60)",
"pp.pprint($0)",
"print('-' * 60)"
],
"description": "Create pretty printer, and print statements"
}
This snippet inserts a pprint
import and a statement surrounded by lines. The snippet tab stops within the print
call, allowing you to immediately type the value you want to debug.
Note: In my case, the "scope"
value is redundant as the snippet is stored within a Python snippets file, but keeping it there is fine.
SystemExit variant
I also have a variant identical to the original one, except for an additional raise SystemExit
at the end.
"Pretty print and exit": {
"scope": "python",
"prefix": "ppe",
"body": [
"import pprint # isort: skip",
"pp = pprint.PrettyPrinter(indent=2)",
"print('-' * 60)",
"pp.pprint($0)",
"print('-' * 60)",
"raise SystemExit"
],
"description": "Create pretty printer, print statements, and a SystemExit"
}
Note: Raising exceptions is a quick way to stop your program where you want it to stop; it is ideal for debugging and ensuring that your prints end up at the bottom of your output.