Pyccolo: Declarative Instrumentation for Python

0.0.85 · active · verified Thu Apr 16

Pyccolo (pronounced like "piccolo") is a library for declarative instrumentation in Python, allowing users to specify *what* instrumentation to perform rather than *how* to implement it. It aims for ergonomics, composability, and portability across various Python versions. It achieves this by embedding instrumentation at the source code level. The library is actively maintained, with the current version being 0.0.85, and supports Python versions from 3.6 up to 3.14 (since v0.0.73).

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a custom tracer that logs statements before execution. It highlights the use of `BaseTracer` and the `should_instrument_file` method to control which files are instrumented, as well as a `before_stmt` event handler.

import pyccolo as pyc

class MyTracer(pyc.BaseTracer):
    def should_instrument_file(self, filename: str) -> bool:
        # Only instrument files ending with 'my_script.py'
        # For broader instrumentation, adjust this logic.
        return 'my_script.py' in filename

    @pyc.before_stmt
    def on_before_statement(self, ret, node, frame, event):
        print(f"Executing statement: {node.lineno}: {node.__class__.__name__}")

# Example usage with a dummy script content
script_content = """
print("Hello from my_script.py")
x = 1 + 2
if x == 3:
    print("x is 3")
"""

# To simulate a file, we can use exec with a custom globals dict
# and then trace its execution within a temporary module scope.
import types
import sys

# Create a dummy module to hold our script content, so should_instrument_file can identify it
my_script_module = types.ModuleType('my_script')
my_script_module.__file__ = '<string>my_script.py'
sys.modules['my_script'] = my_script_module

# Execute the script content within the dummy module's namespace
with MyTracer():
    exec(script_content, my_script_module.__dict__)

# Clean up the dummy module
del sys.modules['my_script']

view raw JSON →