Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #29550 > unrolled thread
| Started by | Peter Otten <__peter__@web.de> |
|---|---|
| First post | 2012-09-20 15:15 +0200 |
| Last post | 2012-09-20 15:15 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: [Q] How to exec code object with local variables specified? Peter Otten <__peter__@web.de> - 2012-09-20 15:15 +0200
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2012-09-20 15:15 +0200 |
| Subject | Re: [Q] How to exec code object with local variables specified? |
| Message-ID | <mailman.957.1348146880.27098.python-list@python.org> |
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
Back to top | Article view | comp.lang.python
csiph-web