Strange behaviour with eval() and globals() copy

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Geert Jansen

    #1

    Strange behaviour with eval() and globals() copy

    -----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

    iQEVAwUBQ7RFwpr PkVOV4lDgAQKK+A f/eEHbkHiUtH79trD sgvyTwY6xTayk+n B2
    nHZL6iD0aRlDfLt ccsP2OTLafJdNwb 764vK6hqQFuvN2o l4v5SVwEnsJ4Evt wKyH
    iJcByEXZSrPjBsC ejKPsoLCCCJ3q8U dkO4zsYsd+xSqCu JAYzfEnSf75yu6P Y3Hh
    N7uzPT626BdUq5w HaWlbAKqtmCfN5k OodgkTE3s7/h9JlP4EeKyF4s5s CFQdJ0jw
    CWXr28gOMcWBvlV LOVSbeDq5/n5YWfaJKpbGYXol v5H9Cyxa4rZ1AMy 628u1DnPa
    he7sX2T0pTNOaeV JGWanSR99jbq2Vx DaiocQdpjUnEHqa USY8YhFTw==
    =lbmj
    -----END PGP SIGNATURE-----

Working...