You're right, standard Python tracebacks can be verbose and visually noisy, especially when the call stack goes deep into libraries. Luckily, several excellent libraries can significantly improve this!
Here are the most popular and effective ways to get concise and pretty tracebacks:
1. rich (Highly Recommended)
rich is a fantastic library for adding beautiful formatting to terminal applications, and its traceback handling is a standout feature.
-
Features: Syntax highlighting, displays source code context, optionally shows local variables, intelligently collapses repetitive frames from libraries.
-
How to use:
- Install:
pip install rich
- Enable automatic traceback handling: Add this near the beginning of your main script:
from rich.traceback import install
install(show_locals=True) # show_locals=True is optional but very helpful
# --- The rest of your code ---
def func_c(x):
# Introduce an error
return 1 / x
def func_b(y):
return func_c(y - 5)
def func_a(z):
return func_b(z * 2)
# Example call that will raise an error
result = func_a(2.5)
print(result)
-
Output: Instead of the standard plain text traceback, rich will output a beautifully formatted, syntax-highlighted traceback with code context and local variable values (if show_locals=True). It often hides frames deep inside standard libraries unless they are directly relevant.
2. pretty_errors
This library focuses specifically on making tracebacks prettier and more readable, often with less setup than rich.
-
Features: Colorized output, simplified paths, configuration options (e.g., hiding specific library paths), clean formatting.
-
How to use:
- Install:
pip install pretty_errors
- Enable: Simply import it at the start of your script.
import pretty_errors
# pretty_errors.configure(...) # Optional: further configuration
# --- The rest of your code ---
def func_c(x):
return 1 / x
def func_b(y):
return func_c(y - 5)
def func_a(z):
return func_b(z * 2)
result = func_a(2.5)
print(result)
-
Output: Provides a colored, cleaner traceback focusing on your code.
3. better_exceptions
An older library, but still effective and used by some. It also provides context and formatting.
-
Features: Adds source code context and variable values to tracebacks.
-
How to use:
- Install:
pip install better_exceptions
- Enable: Set an environment variable
BETTER_EXCEPTIONS=1 before running your script, OR import it.
import better_exceptions
better_exceptions.hook() # Or use the environment variable method
# --- The rest of your code ---
# (Same example code as above)
-
Output: Similar to rich and pretty_errors, it enhances the standard traceback with context and formatting.
4. loguru
If you're already using loguru for logging (which is also highly recommended for better logging), it comes with built-in enhanced exception formatting.
-
Features: Integrates beautiful tracebacks directly into your logging output, highly configurable sinks and formats.
-
How to use:
- Install:
pip install loguru
- Use
logger.catch() or configure sinks appropriately.
from loguru import logger
import sys
# Configure logger (optional, defaults are often good)
logger.add(sys.stderr, format="{time} {level} {message}", level="INFO", colorize=True, backtrace=True, diagnose=True)
def func_c(x):
return 1 / x
def func_b(y):
return func_c(y - 5)
@logger.catch # Decorator to automatically log exceptions from this function
def func_a(z):
return func_b(z * 2)
# Example call
func_a(2.5)
# Or use try...except with logger.exception
try:
result = 1 / 0
except Exception:
logger.exception("An error occurred during calculation")
-
Output: When an exception occurs in a @logger.catch decorated function or is logged via logger.exception(), Loguru prints a rich, informative traceback as part of its log message.
5. Custom sys.excepthook
This is the underlying mechanism many of these libraries use. You can write your own exception hook, but it's significantly more complex than using a pre-built library. You'd use the traceback module to format the exception and then print it. This gives you ultimate control but requires more effort.
import sys
import traceback
from rich.console import Console # Example using rich for formatting
console = Console()
def custom_excepthook(exc_type, exc_value, tb):
# Use rich's traceback rendering within the custom hook
console.print_exception(
exc_type, exc_value, tb,
show_locals=True, # Optional: Show local variables
word_wrap=True
)
# sys.excepthook = sys.__excepthook__ # Uncomment to restore default
sys.excepthook = custom_excepthook
# --- Your code that might raise an exception ---
1 / 0
Which one to choose?
- For general development and beautiful terminal output:
rich is often the top choice due to its comprehensive features and excellent aesthetics. install(show_locals=True) is incredibly helpful for debugging.
- For a simple, focused traceback prettifier:
pretty_errors is very easy to set up (just import it).
- If you're already using
loguru: Leverage its built-in exception formatting (logger.catch, logger.exception).
- For maximum customization (advanced): Write your own
sys.excepthook.
Start with rich or pretty_errors – they provide a massive improvement with minimal effort.