On Oct 1, 2016, at 7:56 PM, Chris Angelico <ros...@gmail.com> wrote:

> On Sun, Oct 2, 2016 at 10:47 AM, Cem Karan <cfkar...@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 :)

Ah, but crashing things is how we learn! :)  

That said, types.CodeType and types.FunctionType appear to be EXACTLY what I'm 
looking for!  Thank you!  Although I have to admit, the built-in docs for 
types.CodeType are concerning... "Create a code object.  Not for the faint of 
heart." Maybe that should be updated to "Here there be dragons"?  I'll poke 
through python's sources to get an idea of how to use codestring argument, but 
I'll probably be asking more questions on here about it.

Thanks,
Cem Karan
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to