tblib: Traceback Serialization Library

3.2.2 · active · verified Sun Mar 29

tblib is a Python library that allows for the serialization of exceptions and tracebacks, enabling them to be pickled and unpickled across different processes. This is particularly useful for robust error handling in multiprocessing or distributed systems like Celery. It also provides methods to create tracebacks from strings or serialize them to and from dictionaries. The current version is 3.2.2, with releases occurring periodically, often for bug fixes and Python version support updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to serialize an exception and its traceback using `tblib` and Python's `pickle` module. First, `pickling_support.install()` is called to enable traceback pickling. Then, `sys.exc_info()` captures the current exception, which is then serialized. Finally, the serialized exception is unpickled and its traceback can be inspected or re-raised. Note that `pickling_support.install()` typically needs to be called in the environment where the exceptions are *created* for full functionality.

import pickle
import sys
from tblib import pickling_support

def problematic_function():
    raise ValueError("Something went wrong!")

try:
    problematic_function()
except Exception:
    # Install pickling support for all imported exceptions
    pickling_support.install()
    exc_type, exc_value, exc_traceback = sys.exc_info()
    # Serialize the exception info
    serialized_exc_info = pickle.dumps((exc_type, exc_value, exc_traceback))

# In another process or later in the same process:

# Deserialize the exception info
deserialized_exc_type, deserialized_exc_value, deserialized_exc_traceback = pickle.loads(serialized_exc_info)

# Re-raise the exception with its original traceback
print(f"Caught: {deserialized_exc_type.__name__}: {deserialized_exc_value}")
print("Original traceback:\n---")
import traceback
traceback.print_tb(deserialized_exc_traceback)
print("---")

view raw JSON →