Better Exceptions
Better Exceptions is a Python library that automatically enhances standard Python traceback outputs, making them significantly more readable and useful for debugging. It achieves this through features like colorization, displaying more context around code lines, and printing relevant variable values at each point in the traceback. The current version is 0.3.3. It has a slow release cadence, with the last significant update (0.2.1) being several years ago, focusing on stability.
Warnings
- breaking Activation mechanism changed in v0.2.1. Previously, `import better_exceptions` was often sufficient for automatic activation. From v0.2.1 onwards, the primary method for automatic, global activation is setting the `BETTER_EXCEPTIONS=1` environment variable. Simply importing the library in newer versions may not activate the enhanced tracebacks without this environment variable or an explicit `better_exceptions.hook()` call.
- gotcha Do not use `better-exceptions` in production environments. It prints detailed local variable values within tracebacks, which can leak sensitive data into logs or error reports. This is a security risk in a production setting.
- gotcha Conflicts with other exception handlers. `better-exceptions` works by replacing `sys.excepthook`. Other libraries or system tools (e.g., Ubuntu's `python3-apport`) that also modify `sys.excepthook` can interfere, preventing `better-exceptions` from functioning correctly or vice-versa.
- gotcha Environment variable `BETTER_EXCEPTIONS=1` is not persistent by default on Linux/OSX. Using `export` only sets it for the current terminal session.
- gotcha There is a popular Sims 4 game mod also named 'Better Exceptions'. When searching for troubleshooting or usage information, ensure you are referencing documentation for the Python library and not the game mod, as they are entirely unrelated projects.
Install
-
pip install better_exceptions
Imports
- better_exceptions
import better_exceptions
Quickstart
import os
os.environ['BETTER_EXCEPTIONS'] = '1'
def divide_by_zero():
a = 10
b = 0
return a / b
if __name__ == '__main__':
try:
divide_by_zero()
except ZeroDivisionError:
print("\n--- Better Exceptions Output (if enabled) ---")
# The traceback will be formatted by better-exceptions if the hook is active.
# This print statement is just to show where the formatted output would appear.
raise # Re-raise to show the formatted traceback