Byte code descriptions somewhere?

Chris Angelico rosuav at gmail.com
Sat Oct 1 19:56:51 EDT 2016


On Sun, Oct 2, 2016 at 10:47 AM, Cem Karan <cfkaran2 at gmail.com> wrote:
> Cool, thank you!  Quick experimentation suggests that I don't need to worry about marking anything for garbage collection, correct?  The next question is, how do I create a stream of byte codes that can be interpreted by CPython directly?  I don't mean 'use the compile module', I mean writing my own byte array with bytes that CPython can directly interpret.
>

"Marking for garbage collection" in CPython is done by refcounts; the
bytecode is at a higher level than that.

>>> dis.dis("x = y*2")
  1           0 LOAD_NAME                0 (y)
              3 LOAD_CONST               0 (2)
              6 BINARY_MULTIPLY
              7 STORE_NAME               1 (x)
             10 LOAD_CONST               1 (None)
             13 RETURN_VALUE

A LOAD operation will increase the refcount (a ref is on the stack),
BINARY_MULTIPLY dereferences the multiplicands and adds a ref to the
product, STORE will deref whatever previously was stored, etc.

To execute your own code, look at types.FunctionType and
types.CodeType, particularly the latter's 'codestring' argument
(stored as the co_code attribute). Be careful: you can easily crash
CPython if you mess this stuff up :)

ChrisA



More information about the Python-list mailing list