Strange behaviour with eval() and globals() copy

G

Geert Jansen

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi,

I'm experiencing a weird problem with eval(), providing it a copy of
the globals() dictionary.

The following code works:

<snip>
s = """
def func(level):
if level < 2:
func(level+1)
func(0)
"""
c = compile(s, '<string>', 'exec')
g = globals()
#g = g.copy()
l = locals()
eval(c, g, l)
</snip>

But if I comment in the line "g = g.copy()" and run the same snippet
again, I get the following error:

Traceback (most recent call last):
File "test.py", line 12, in ?
eval(c, g, l)
File "<string>", line 5, in ?
File "<string>", line 4, in func
NameError: global name 'func' is not defined

Any ideas?

Basically I'm trying to evaluate code with a specific global and local
namespace. However, I cannot get this to work unless I use the exact
global namespace as returned by globals(), any other mapping makes
this code fail.

Python version is 2.4.2 on Linux.

Regards,
Geert


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iQEVAwUBQ7RFwprPkVOV4lDgAQKK+Af/eEHbkHiUtH79trDsgvyTwY6xTayk+nB2
nHZL6iD0aRlDfLtccsP2OTLafJdNwb764vK6hqQFuvN2ol4v5SVwEnsJ4EvtwKyH
iJcByEXZSrPjBsCejKPsoLCCCJ3q8UdkO4zsYsd+xSqCuJAYzfEnSf75yu6PY3Hh
N7uzPT626BdUq5wHaWlbAKqtmCfN5kOodgkTE3s7/h9JlP4EeKyF4s5sCFQdJ0jw
CWXr28gOMcWBvlVLOVSbeDq5/n5YWfaJKpbGYXolv5H9Cyxa4rZ1AMy628u1DnPa
he7sX2T0pTNOaeVJGWanSR99jbq2VxDaiocQdpjUnEHqaUSY8YhFTw==
=lbmj
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top