[Q] How to exec code object with local variables specified?

Peter Otten __peter__ at web.de
Fri Sep 21 03:42:32 EDT 2012


Makoto Kuwata wrote:

> On Thu, Sep 20, 2012 at 10:15 PM, Peter Otten <__peter__ at web.de> wrote:
>>
>>>>> loc = {}
>>>>> exec("x = 1; y = 2", globals(), loc)
>>>>> loc
>> {'y': 2, 'x': 1}
>>
>> However, this won't work with the code object taken from a function which
>> uses a different a bytecode (STORE_FAST instead of STORE_NAME):
>>
> 
> Is there any way to use STORE_FAST instead of STORE_NAME?
> 
> exec("string", ...) is not a solution for me.

Can you describe your use-case? Perhaps we can suggest an alternative 
approach.
 
> # What is different between fn.func_code and compile("string")?

func_code has faster bytecode at the expense of flexibility.




More information about the Python-list mailing list