Skip to main content

bytecode manipulation (byteplay) library for Python 3

Project description

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

About byteplay

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)
3 5
>>> from byteplay3 import *
>>> # convert the code object of function f to a Code object
>>> c = Code.from_code(f.__code__)
>>> c
<byteplay3.Code object at 0x1030da3c8>
>>> # display the bytecode tuples in the Code object
>>> print( c.code )
2 1 LOAD_GLOBAL print

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()
>>> f(3,5)
5 3

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for byteplay3, version 3.5.0
Filename, size File type Python version Upload date Hashes
Filename, size byteplay3-3.5.0.tar.gz (23.4 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page