local variables in exec

Steve Holden sholden at holdenweb.com
Mon Dec 17 15:58:03 CET 2001


"Jeremy Lowery" <jslowery at hotmail.com> wrote ...
> a snipplet would be describe this.
> >>> x = 100
> >>> def f():
> ...  print x
> ...
> >>> f()
> 100
> >>> lns = {x: '4500'}
> >>> fc = 'def f(): print x'
> >>> bc = compile(fc, '', 'exec')
> >>> exec bc in lns
> >>> lns['f']()
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "", line 1, in f
> NameError: global name 'x' is not defined
> >>>
>
> why doesn't this work?

Because you have stored 4500 in the lns dictionary under the key 100. Use
the variable name as a string and it works as you expect (but realise you
are doing things with a high horribleness quotient: while it is occasionally
necessary to descend to such depths, one should avoid it where possible).

>>> lns = {"x": "4500"}
>>> fc = "def f(): print x"
>>> bc = compile(fc, "", "exec")
>>> exec bc in lns
>>> lns['f']()
4500
>>>

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list