ANN: pkalk, and problems with "exec foo in g,v"

Erik Max Francis max at alcyone.com
Tue Dec 24 19:32:57 EST 2002


Gerson Kurz wrote:

> >>> g,v={}, {}

These are the global and local dictionaries, respectively.

> >>> exec "from math import *" in g, v
> >>> exec "a = lambda x:sin(x)" in g, v
> >>> exec "sin(2)" in g, v
> >>> exec "a(2)" in g, v
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<string>", line 1, in ?
>   File "<string>", line 1, in <lambda>
> NameError: global name 'sin' is not defined
> 
> So, my problem is this: I'm using "exec foo in g,v" for statement
> evaluation. I can import math, and conveniently use the math stuff
> (its a calculator, after all). I cannot, however, define a local
> lambda that uses the "global" scope in g,v. Is that a bug or a
> feature?

When you include the local dictionary, by default assignments go in
there.  So in your satement

	exec "from math import *" in g, v

the contents of the math module went in the _local_ dictionary v, not
the global one, g.  This probably isn't what you wanted; you probably
wanted those names to go into the global dictionary, not the local one. 
Unless you specifically want to muck around with locals, use

	exec S in g

instead without specifying the locals dictionary.

>>> g, l = {}, {} # I renamed your v to l to be a little clearer
>>> exec "from math import *" in g
>>> g['sin']
<built-in function sin>
>>> exec "a = lambda x: sin(x)" in g, l
>>> l['a']
<function <lambda> at 0x815a6f4>
>>> exec "a(2)" in g, l

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Dead men have no victory.
\__/ Euripides
    Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/
 A personal guide to Aliens vs. Predator 2.



More information about the Python-list mailing list