This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author beazley
Recipients beazley
Date 2009-01-04.14:52:35
SpamBayes Score 2.3855202e-05
Marked as misclassified No
Message-id <1231080757.34.0.371299910719.issue4831@psf.upfronthosting.co.za>
In-reply-to
Content
Please forgive me, but I'm really trying to wrap my brain around the 
behavior of exec() in Python 3.   Here's a quote from the documentation:

   "In all cases, if the optional parts are omitted, the code is
    executed in the current scope."

This is referring to the optional use of the globals/locals parameters 
and seems to indicate that if they're omitted the code executes in the 
scope where the exec() appeared.

Yet, this code fails:

def foo():
    exec("a = 42")
    print(a)         # NameError: a

Now, I realize that exec() became a function in Python 3.  However, 
regardless of that, is it really the intent that exec() not be allowed 
to ever modify any local variable of a function?   In other words, do I 
really have to do this?

def foo():
    ldict = locals()
    exec("a=42",globals(),ldict)
    a = ldict['a']
    print(a)

I submitted a bug report about this once before and it was immediately 
dismissed.   

I would appreciate some greater clarity on this matter this go around.  
Specifically, what is the approved way to have exec() modify the local 
environment of a function?
History
Date User Action Args
2009-01-04 14:52:37beazleysetrecipients: + beazley
2009-01-04 14:52:37beazleysetmessageid: <1231080757.34.0.371299910719.issue4831@psf.upfronthosting.co.za>
2009-01-04 14:52:36beazleylinkissue4831 messages
2009-01-04 14:52:35beazleycreate