By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,155 Members | 952 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,155 IT Pros & Developers. It's quick & easy.

Strange behaviour with eval() and globals() copy

P: n/a
-----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
nHZL6iD0aRlDfLtccsP2OTLafJdNwb764vK6hqQFuvN2ol4v5S VwEnsJ4EvtwKyH
iJcByEXZSrPjBsCejKPsoLCCCJ3q8UdkO4zsYsd+xSqCuJAYzf EnSf75yu6PY3Hh
N7uzPT626BdUq5wHaWlbAKqtmCfN5kOodgkTE3s7/h9JlP4EeKyF4s5sCFQdJ0jw
CWXr28gOMcWBvlVLOVSbeDq5/n5YWfaJKpbGYXolv5H9Cyxa4rZ1AMy628u1DnPa
he7sX2T0pTNOaeVJGWanSR99jbq2VxDaiocQdpjUnEHqaUSY8Y hFTw==
=lbmj
-----END PGP SIGNATURE-----

Dec 29 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.