On eval and its substitution of globals
Paddy
paddy3118 at netscape.net
Sat Feb 19 10:49:30 EST 2005
Hi,
I got tripped up on the way eval works with respect to modules and
so wrote a test.
It seems that a function carries around knowledge of the globals()
present
when it was defined. (The .func_globals attribute)?
When evaluated using eval(...) the embedded globals can be overridden
with
the one passed through the eval(...) call
If however you create a new function that calls the first then eval's
global argument is only substituted in the outer call!
TEST:
=====
Python 2.4 (#2, Jan 8 2005, 20:18:03)
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> globals().has_key('A')
False
>>> globals().has_key('B')
False
>>> def f1(): return A < B
...
>>> def z(): return f1()
...
>>> eval(f1.func_code,dict(A=1,B=2))
True
>>> eval(z.func_code,dict(A=1,B=2, f1=f1))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in z
File "<stdin>", line 1, in f1
NameError: global name 'A' is not defined
>>>
ENDTEST
=======
Is there a way to do a deep substitution of the globals?
I should add that f1 is given as-is. I can modify z,
and f1 is just one of many functions given and function z
is some boolean function of the f<n>'s
Thanks, Pad.
More information about the Python-list
mailing list