ANN: byteplay - a bytecode assembler/disassembler

spam.noam at spam.noam at
Mon Aug 14 21:34:10 CEST 2006


I would like to present a module that I have wrote, called byteplay.
It's a Python bytecode assembler/disassembler, which means that you can
take Python code object, disassemble them into equivalent objects which
are easy to play with, play with them, and then assemble a new,
modified, code object.

I think it's pretty useful if you like to learn more about Python's
bytecode - playing with things and seeing what happens is a nice way to
learn, I think.

Here's a quick example. We can define this stupid function:

>>> def f(a, b):
...     print (a, b)
>>> f(3, 5)
(3, 5)

We can convert it to an equivalent object, and see how it stores the
byte code:

>>> from byteplay import *
>>> c = Code.from_code(f.func_code)
>>> from pprint import pprint; pprint(c.code)
[(SetLineno, 2),
 (LOAD_FAST, 'a'),
 (LOAD_FAST, 'b'),
 (PRINT_ITEM, None),
 (LOAD_CONST, None),

We can change the bytecode easily, and see what happens. Let's insert a
ROT_TWO opcode, that will swap the two arguments:

>>> c.code[3:3] = [(ROT_TWO, None)]
>>> f.func_code = c.to_code()
>>> f(3, 5)
(5, 3)

You can download byteplay from and you can read
(and edit) the documentation at
. I will be happy to hear if you find it useful, or if you have any
comments or ideas.

Have a good day,
Noam Raphael

More information about the Python-announce-list mailing list