[New-bugs-announce] [issue43481] PyEval_EvalCode() namespace issue not observed in Python 2.7.

Chris Morton report at bugs.python.org
Fri Mar 12 16:44:37 EST 2021


New submission from Chris Morton <chrisgmorton at yahoo.com>:

Compiling (Window 10, MSVS 16):

#include <Python.h>

int main(int argc, char* argv[])
{
    const char* code = "c=[1,2,3,4]\nd={'list': [c[i] for i in range(len(c))]}\nprint(d)\n";

    Py_Initialize();

    PyObject* pycode = Py_CompileString(code, "", Py_file_input );   
    PyObject* main_module = PyImport_AddModule("__main__");
    PyObject* global_dict = PyModule_GetDict(main_module);
    PyObject* local_dict = PyDict_New();
    
    PyEval_EvalCode(pycode, global_dict, local_dict);  // (PyCodeObject*) pycode in Python 2.7
    
    Py_Finalize();

    return 0;

and executing yields:

Traceback (most recent call last):
  File "", line 2, in <module>
  File "", line 2, in <listcomp>
NameError: name 'c' is not defined

While not particularly clever python code, it is not clear why the reference c is not in scope having previously been defined. Replacing the clumsy list comprehension using range() with c[:] or [ci for ci in c] produces the expected result:

{'list': [1, 2, 3, 4]}

This issue is not observed with Python 2.7 (.18).

----------
components: C API
messages: 388557
nosy: chrisgmorton
priority: normal
severity: normal
status: open
title: PyEval_EvalCode() namespace issue not observed in Python 2.7.
versions: Python 3.8

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


More information about the New-bugs-announce mailing list