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 terry.reedy
Recipients docs@python, techtonik, terry.reedy
Date 2012-02-25.00:15:24
SpamBayes Score 1.7877033e-11
Marked as misclassified No
Message-id <1330128925.46.0.887599529886.issue14049@psf.upfronthosting.co.za>
In-reply-to
Content
Searching on 'exec NameError' shows that this issue is a duplicate of (behavior issue) #1167300 which contained an essentially identical example"

>>> exec """\
... x = 3
... def f():
...     print x
... f()
... """ in {}, {}

#1167300 was closed as a duplicate of (behavior issue) #991196, which in turn was closed as 'won't fix' (ie, works as it must). Doc issue #4831, which resulted in some doc changes, seems related to this but is not the same. I believe this issue is a duplicate of #13557, which has a patch. I will add my proposed change there.

Anyway, my comments:

In 3.2.2, this runs

#prog='''\
x = 1
def weird():
    y = x + 1
    return y
print(weird())
#'''
#exec(prog)

The same uncommented does also, as does adding ',{}' to the call.
Adding ',{},{}' gives the NameError.
With one named {} arg passed twice, as follows, it runs.

d = {}
exec(prog, d, d)

The reasons for these results are:
1. assignments are *always* to the local namespace.
2. normally, for module code, the local and global namespaces are the same.
3. in the example, 'x=1' is the same as "values['x']=1", while within the function, 'y=x+1' looks up x in gvalues.

This is the same explanation as given in #1167300.
History
Date User Action Args
2012-02-25 00:15:25terry.reedysetrecipients: + terry.reedy, techtonik, docs@python
2012-02-25 00:15:25terry.reedysetmessageid: <1330128925.46.0.887599529886.issue14049@psf.upfronthosting.co.za>
2012-02-25 00:15:24terry.reedylinkissue14049 messages
2012-02-25 00:15:24terry.reedycreate