[New-bugs-announce] [issue38331] Exec not recognizing global variables inside function

Huyston report at bugs.python.org
Mon Sep 30 16:39:38 EDT 2019


New submission from Huyston <prajogaosu at gmail.com>:

This seems like a bug for me, forgive me if its not.

Consider the following script:

def func():
    print(var)

my_globals = {'func':func,'var':14}
exec("print(var);func()",my_globals,my_globals)

This is the output:

14
Traceback (most recent call last):
  File "bug.py", line 5, in <module>
    exec("print(var);func()",my_globals,my_globals)
  File "<string>", line 1, in <module>
  File "bug.py", line 2, in func
    print(var)
NameError: name 'var' is not defined

The first line gives the expected result (14). However the second line throws the NameError.

If 'func' is defined inside the exec argument string, then it prints 14 and 14, which is the expected result (for me at least).

Ex:

def func():
    print(var)

my_globals = {'func':func,'var':14}
exec("def func():\n    print(var)\nprint(var);func()",my_globals,my_globals)

Result:
14
14

So is this really a bug or is this the expected behavior somehow?

----------
components: Interpreter Core
messages: 353622
nosy: Huyston
priority: normal
severity: normal
status: open
title: Exec not recognizing global variables inside function
type: behavior
versions: Python 3.7

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


More information about the New-bugs-announce mailing list