[New-bugs-announce] [issue42190] global declarations affect too much inside exec or compile

Kevin Shweh report at bugs.python.org
Thu Oct 29 01:07:31 EDT 2020


New submission from Kevin Shweh <kevin.shweh at gmail.com>:

A global declaration inside a function is only supposed to affect assignments inside that function, but in code executed with exec, a global declaration affects assignments outside the function:

>>> gdict = {}
>>> ldict = {}
>>> exec('x = 1', gdict, ldict)
>>> 'x' in gdict
False
>>> 'x' in ldict
True
>>> 
>>> gdict = {}
>>> ldict = {}
>>> exec('''
... x = 1
... def f(): global x''', gdict, ldict)
>>> 'x' in gdict
True
>>> 'x' in ldict
False

Here, we can see that the presence of a "global x" declaration inside f causes the "x = 1" outside of f to assign to globals instead of locals. This also affects code objects compiled with compile().

----------
components: Interpreter Core
messages: 379855
nosy: Kevin Shweh
priority: normal
severity: normal
status: open
title: global declarations affect too much inside exec or compile
type: behavior
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42190>
_______________________________________


More information about the New-bugs-announce mailing list