G
Guest
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:
(3, 5)
We can convert it to an equivalent object, and see how it stores the
byte 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:
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
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:
(3, 5)
We can convert it to an equivalent object, and see how it stores the
byte 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:
(5, 3)c.code[3:3] = [(ROT_TWO, None)]
f.func_code = c.to_code()
f(3, 5)
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