codetransformer¶
Bytecode transformers for CPython inspired by the ast
module’s
NodeTransformer
.
codetransformer
is a library that provides utilities for working with
CPython bytecode at runtime. Among other things, it provides:
- A
Code
type for representing and manipulating Python bytecode. - An
Instruction
type, withsubclasses
for each opcode used by the CPython interpreter. - A
CodeTransformer
type providing a pattern-based API for describing transformations onCode
objects. Example transformers can be found incodetransformer.transformers
. - An experimental
decompiler
for determining the AST tree that would generate a code object.
The existence of codetransformer
is motivated by the desire to override
parts of the python language that cannot be easily hooked via more standard
means. Examples of program transformations made possible using code
transformers include:
- Overriding the
is
andnot
operators. - Overloading Python’s data structure literals.
- Optimizing functions by freezing globals as constants.
- Exception handlers that match on exception instances.
Contents: