Why Aren't Globals Copied When I Run Eval With A Globals Argument?
I'm having difficulty understanding how eval() behaves regarding the globals used in the evaluated expression. For example, the following script prints 1: x = 1 print eval('x') Wh
Solution 1:
This appears to be a bug. Whether it's a bug in the documentation or the implementation, I don't know, but eval
does not copy the current globals into globals
if __builtins__
is not present. Rather, it only copies __builtins__
:
if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
if (PyDict_SetItemString(globals, "__builtins__",
PyEval_GetBuiltins()) != 0)
returnNULL;
}
I didn't find anything about this on the Python bug tracker, and the discrepancy is still present in 3.4 and the current dev branch, so it may be worth submitting a bug report and a proposed documentation correction:
If the globals dictionary is present and lacks ‘
__builtins__
’, the current__builtins__
is copied into globals before expression is parsed.
Post a Comment for "Why Aren't Globals Copied When I Run Eval With A Globals Argument?"