New submission from Kevin Shweh <kevin.sh...@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 <rep...@bugs.python.org>
<https://bugs.python.org/issue42190>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to