DEV Community

Yusuke Minami
Yusuke Minami

Posted on

1

An alternative way to debug your Python code

Rich Exception

Python developers use print(variable_foobar) or debugging feature of IDE such as VS Code to troubleshoot, but aren't there any quicker alternative ways?

rich package can make the exception traceback nicer; show the local variable values and extra lines of code.

Image description

How to use

  1. Install rich
pip install -U rich
Enter fullscreen mode Exit fullscreen mode
  1. Place the following code in the beginning of your main module.
try:
    from rich.traceback import install

    install(
        console=None,
        width=200,
        extra_lines=3,
        theme=None,
        word_wrap=True,
        show_locals=True,
        locals_max_length=10,
        locals_max_string=80,
        locals_hide_dunder=True,
        locals_hide_sunder=None,
        indent_guides=True,
        suppress=(),
        max_frames=20,
    )
except Exception:
    print("Failed to set up rich traceback. Try: pip install -U rich")
Enter fullscreen mode Exit fullscreen mode

Alternatively, to apply to all the codes you run, you may place the Python code in sitecustomize.py file in site-packages directory which can be found by running:

python -c "import sys;print(sys.path)"
Enter fullscreen mode Exit fullscreen mode

References

Regarding the options, see the documents:

https://rich.readthedocs.io/en/stable/traceback.html#traceback-handler
https://rich.readthedocs.io/en/stable/reference/traceback.html#rich.traceback.install

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay