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 chrisgmorton
Recipients chrisgmorton
Date 2021-03-12.21:44:36
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1615585477.01.0.106665214672.issue43481@roundup.psfhosted.org>
In-reply-to
Content
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).
History
Date User Action Args
2021-03-12 21:44:37chrisgmortonsetrecipients: + chrisgmorton
2021-03-12 21:44:37chrisgmortonsetmessageid: <1615585477.01.0.106665214672.issue43481@roundup.psfhosted.org>
2021-03-12 21:44:36chrisgmortonlinkissue43481 messages
2021-03-12 21:44:36chrisgmortoncreate