ANN: byteplay - a bytecode assembler/disassembler
Hello, 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'), (BUILD_TUPLE, 2), (PRINT_ITEM, None), (PRINT_NEWLINE, None), (LOAD_CONST, None), (RETURN_VALUE, 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 http://byteplay.googlecode.com/svn/trunk/byteplay.py and you can read (and edit) the documentation at http://wiki.python.org/moin/ByteplayDoc . 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
participants (1)
-
spam.noam@gmail.com