Package: pyccolo
PyccoloPyccolo (pronounced like the instrument "piccolo") is a library for declarative
instrumentation in Python; i.e., it lets you specify thewhatof the
instrumentation you wish to perform, and takes care of thehowfor you.  It
aims to beergonomic,composable, andportable, by providing an intuitive
interface, making it easy to layer multiple levels of instrumentation, and
allowing the same code to work across multiple versions of Python (3.6 to
3.12), with few exceptions. Portability across versions is accomplished by
embedding instrumentation at the level of source code (as opposed to
bytecode-level instrumentation).Pyccolo can be used (and has been used) to implement various kinds of dynamic analysis
tools and other instrumentation:Code coverage (seepyccolo/examples/coverage.py)Syntactic macros such as quasiquotes (likeMacroPy's) or quick lambdas; seepyccolo/examples/quasiquote.pyandpyccolo/examples/quick_lambda.pySyntax-augmented Python (3.8 and up, seepyccolo/examples/optional_chaining.py)Dynamic dataflow analysis performed byipyflowTools to perform (most) imports lazily (seepyccolo/examples/lazy_imports.py)Tools to uncoversemantic memory leaks<Your tool here!>InstallpipinstallpyccoloHello WorldBelow is a simple script that uses Pyccolo to print "Hello, world!" before
every statement that executes:importpyccoloaspycclassHelloTracer(pyc.BaseTracer):@pyc.before_stmtdefhandle_stmt(self,*_,**__):print("Hello, world!")if__name__=="__main__":withHelloTracer:# prints "Hello, world!" 11 timespyc.exec("for _ in range(10): pass")Instrumentation is provided by atracer classthat inherit frompyccolo.BaseTracer. This class rewrites Python source code with
instrumentation that triggers whenever events of interest occur, such as when a
statement is about to execute. By registering a handler with the associated
event (with the@pyc.before_stmtdecorator, in this case), we can enrich our
programs with additional observability, or even alter their behavior
altogether.What is up withpyc.exec(...)?A program's abstract syntax tree is fixed at import / compile time, and when
our script initially started running, the tracer was not active, so unquoted
Python in the same file will lack instrumentation. It is possible to instrument
modules at import time, but only when the imports are performed inside a
tracing context. Thus, we must quote any code appearing in the same module
where the tracer class was defined in order to instrument it.Composing tracersA core feature of Pyccolo is that its instrumentation iscomposable.  It's
usually tricky to use two or moreast.NodeTransformerclasses simultaneously
--- sometimes you can just have one inherit from the other, but if they both
definevisitmethods for the same AST node type, then typically you would
need to define a bespoke node transformer that uses logic from each base
transformer, handling corner cases to resolve incompatibilities.  With Pyccolo,
you simply compose the context managers of each tracer class whose
instrumentation you wish to use, and everything usually Just
WorksTM:withtracer1:withtracer2:pyc.exec(...)Compatibility with sys.settrace(...)Pyccolo is designed to support not only AST-level instrumentation, but also
instrumentation involving Python'sbuilt in tracing
utilities.
To use it, you simply register handlers for one of the corresponding
Pyccolo events (call,line,return_,exception, oropcode).
Here's a minimal example:importpyccoloaspycclassSysTracer(pyc.BaseTracer):@pyc.calldefhandle_call(self,*_,**__):print("Pushing a stack frame!")@pyc.return_defhandle_return(self,*_,**__):print("Popping a stack frame!")if__name__=="__main__":withSysTracer:deff():defg():return42returng()# push, push, pop, popanswer_to_life_universe_everything=f()Note that we didn't need to usepyc.exec(...)in the above example, because Python's built-in
tracing does not involve any AST-level transformations. If, however, we had registered handlers
for other events, such aspyc.before_stmt, we would need to usepyc.exec(...)to ensure those
handlers get called, when running code in the same file where our tracer class is defined.What if I'm already using sys.settrace(...) with my own tracing function?Pyccolo is designed to becomposable, and should execute both your tracing function as well
as any handlers defined in any active Pyccolo tracers. For example Pyccolo's unit tests forcallandreturnevents work even whencoverage.pyis active (and without breaking it), which also uses Python's built-in tracing utilities.Instrumenting Imported ModulesInstrumentation is opt-in for modules imported within tracing contexts. To determine whether
a module gets instrumented, the methodshould_instrument_file(...)is called with the module's
corresponding filename as input. For example:classMyTracer(pyc.BaseTracer):defshould_instrument_file(self,filename:str)->bool:returnfilename.endswith("foo.py")# handlers, etc. defined below...withMyTracer:importfoo# contents of `foo` module get instrumentedimportbar# contents of `bar` module do not get instrumentedImports are instrumented by registering a custom finder / loader withsys.meta_path.
This loader ignores cached bytecode (which may possibly be uninstrumented), and avoids
generatingnewcached bytecode (which would be instrumented, possibly causing confusion
later when instrumentation is not desired).Command Line InterfaceYou can execute arbitrary scripts with instrumentation enabled with thepyccommand line tool.
For example, to use theOptionalChainertracer defined inpyccolo/examples/optional_chaining.py,
you can callpycas follows, given some example scriptbar.py:# bar.pybar=None# prints `None` since bar?.foo coalesces to `None`print(bar?.foo)>pycbar.py-tpyccolo.examples.OptionalChainerYou can also runbaras a module (indeed,pycperforms this internally when provided a file):>pyc-mbar-tpyccolo.examples.OptionalChainerNote that you can specify multiple tracer classes after the-targument;
in case you were not already aware, Pyccolo is composable! :)The above example demonstrates a tracer class that performs syntax augmentation on its
instrumented Python source to modify the default Python syntax. This feature is available
only on Python >= 3.8 for now and is lacking documentation for the moment, but you can
see some examples in thetest_syntax_augmentation.pyunit tests.More EventsPyccolo handlers can be registered for many kinds of events. Some of the more common ones are:pyc.before_stmt, emitted before a statement executes;pyc.after_stmt, emitted after a statement executes;pyc.before_attribute_load, emitted inload contextsbefore an attribute is accessed;pyc.after_attribute_load, emitted in load contexts after an attribute is accessed;pyc.load_name, emitted when a variable is used in a load context (e.g.fooinbar = foo.baz);pyc.callandpyc.return_, two non-AST trace events built-in to Python.There are many different Pyccolo events, and more are always being added. Seepyccolo/trace_events.pyfor a full list.Note that, for AST events, Python source is only transformed to emit some event
when there is at least one tracer active that has at least one handler
registered for that event. This prevents the transformed source from becoming
extremely bloated when only a few events are needed.Handler InterfaceEvery Pyccolo handler is passed four positional arguments:The return value, for instrumented expressions;The AST node (or node id, if usingregister_raw_handler(...), orNone, forsysevents);The stack frame, at the point where instrumentation kicks in;The event (useful when the same handler is registered for multiple events).Some events pass additional keyword arguments, which I'm still in the process
of documenting, but the above four tend to suffice for most use cases.Not every handler receives a return value; for example, this argument is alwaysNoneforpyc.after_stmthandlers. For certain handlers, the return value
can be overridden. For example, by returning a value in apyc.before_attribute_load, we override the object whose attribute is
accessed. If we return nothing orNone, then we do not override this object.
(If we actually want to override it asNonefor some reason, then we can
returnpyc.Null.) For a particular event, handler return values compose with
other handlers defined on the same tracer class as well as with handlers
defined on other tracer classes.PerformancePyccolo instrumentation adds significant overhead to Python. In some
cases, this overhead can be partially mitigated if, for example, you only need
instrumentation the first time a statement runs. In such cases, you can
deactivate instrumentation after, e.g., the first time a function executes, or
after the first iteration in a loop for that respective function or loop, so
that further calls (iterations, respectively) use uninstrumented code with all
the mighty performance of native Python. This is implemented by activating
"guards" associated with the function or loop, as in the below example:classTracesOnce(pyc.BaseTracer):@pyc.register_raw_handler((pyc.after_for_loop_iter,pyc.after_while_loop_iter))defafter_loop_iter(self,*_,guard,**__):self.activate_guard(guard)@pyc.register_raw_handler(pyc.after_function_execution)defafter_function_exec(self,*_,guard,**__):self.activate_guard(guard)Subsequent calls / iterations will be instrumented only after callingself.deactivate_guard(...)on the associated function / loop guard.LicenseCode in this project licensed under theBSD-3-Clause License.