Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: [Q] How to exec code object with local variables specified?

Reply
Thread Tools

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

 
 
Peter Otten
Guest
Posts: n/a
 
      09-20-2012
Makoto Kuwata wrote:

> Is it possible to run code object with local variables specified?
> I'm trying the following code but not work:
>
> def fn():
> x = 1
> y = 2
> localvars = {'x': 0}
> exec(fn.func_code, globals(), localvars)
> print(localvars)
> ## what I expected is: {'x': 1, 'y': 2}
> ## but actual is: {'x': 0}
>
> Python: 2.7.3


>>> 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):


>>> import dis
>>> def f(): x = 1

....
>>> dis.dis(f)

1 0 LOAD_CONST 1 (1)
3 STORE_FAST 0 (x)
6 LOAD_CONST 0 (None)
9 RETURN_VALUE
>>> dis.dis(compile("x=1", "<nofile>", "exec"))

1 0 LOAD_CONST 0 (1)
3 STORE_NAME 0 (x)
6 LOAD_CONST 1 (None)
9 RETURN_VALUE


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
[Q] How to exec code object with local variables specified? Makoto Kuwata Python 2 09-21-2012 08:20 PM
Re: [Q] How to exec code object with local variables specified? Peter Otten Python 0 09-21-2012 07:42 AM
Re: [Q] How to exec code object with local variables specified? Terry Reedy Python 0 09-20-2012 04:18 PM
Re: [Q] How to exec code object with local variables specified? Makoto Kuwata Python 0 09-20-2012 03:40 PM



Advertisments