<p dir="ltr">On Apr 1, 2015 3:02 PM, "Andrew Barnert" <abarnert@yahoo.com.dmarc.invalid> wrote:<br>
><br>
> On Wednesday, April 1, 2015 12:40 PM, Ron Adam <<a href="mailto:ron3200@gmail.com">ron3200@gmail.com</a>> wrote:<br>
> > When exec is given a code object, it call's PyEval_EvalCodeEx in<br>
> > ceval.c directly with local and global dictionaries.  (That should answer<br>
> > some of your comments as to why I uses the dictionary.)<br>
><br>
> Yes, and running the block of code directly with the local and global dictionaries is exactly what you want it to do, so why are you telling it not to do that?<br>
><br>
> For example:<br>
><br>
><br>
>     def macro():<br>
>         x += 1<br>
>     code = fix_code(macro.__code__)<br>
><br>
>     def f(code_obj):<br>
>         x = 1<br>
>         loc = locals()<br>
>         eval(code_obj)<br>
>         return loc['x']<br>
><br>
> (Or, if you prefer, use "run_code_obj" instead of "eval".)<br>
><br>
> The problem here is that if you just "return x" at the end instead of "return loc['x']", you will likely see 1 instead of 2. It's the same problem you get if you "exec('x += 1')", exactly as described in the docs.<br>
><br>
> That happens because f was compiled to look up x by index in the LOAD_FAST locals array, instead of by name in the locals dict, but your modified code objects mutate only the dict, not the array. That's the big problem you need to solve. Adding more layers of indirection doesn't get you any closer to fixing it.</p>
<p dir="ltr">You can propagate changes to the dict back to the array by calling the c api function PyFrame_LocalsToDict. It's pretty easy to do via ctypes, see e.g. </p>
<p dir="ltr"><a href="http://pydev.blogspot.com/2014/02/changing-locals-of-frame-frameflocals.html?m=1">http://pydev.blogspot.com/2014/02/changing-locals-of-frame-frameflocals.html?m=1</a></p>
<p dir="ltr">I guess you could append some byte code to do this to your modified function bodies.</p>
<p dir="ltr">-n</p>