byteplay lets you convert Python code objects into equivalent objects which are easy to play with, and lets you convert those objects back into Python code objects. It's useful for applying transformations on Python functions, and is also useful in learning Python byte code intricacies. This version works with Python 3.4 and 3.5.
For the full documentation see the "about" file located at
byteplay3 is a module which lets you easily play with Python bytecode.
The basic idea is simple: define a new type named Code which is equivalent
to Python code objects, but Code objects, unlike Python code objects,
are easy to play with. Any Python code object can be converted to
a Code object, and vice-versa, without losing any important information.
Within a Code object, the bytecode instructions are represented in a
way that is easy to examine and modify.
This module, byteplay3, is based on the original by Noam Raph, which
is still available from pypi. If you have code that used byteplay under
Python 2, you can migrate to Python 3 just by changing your import line
to read "from byteplay3 import *". For minor incompatibilities, see the
"about" file linked above. Of course you will find more than minor
incompatibilities in Python 3's bytecode, which is considerably changed.
A Quick Example
Start with a silly function, convert its code to a Code object and display it::
>>> def f(a, b):
... print(a, b)
>>> f(3, 5)
>>> from byteplay3 import *
>>> # convert the code object of function f to a Code object
>>> c = Code.from_code(f.__code__)
<byteplay3.Code object at 0x1030da3c8>
>>> # display the bytecode tuples in the Code object
>>> print( c.code )
2 1 LOAD_GLOBAL print
2 LOAD_FAST a
3 LOAD_FAST b
4 CALL_FUNCTION 2
6 LOAD_CONST None
Ok, now let's play! Say we want to change the function so it prints its
arguments in reverse order. To do this, we will insert a ROT_TWO opcode
after the two arguments were loaded to the stack. (That is, after
LOAD_FAST b and before CALL_FUNCTION 2.)::
>>> c.code[4:4] = [(ROT_TWO,None)]
Then replace the code object in function f with a new one::
>>> f.__code__ = c.to_code()
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.