-
-
Notifications
You must be signed in to change notification settings - Fork 32k
exec docs should note that the no argument form in a local scope is really the two argument form #68988
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
The following script demonstrates a bug in the exec() function in Python 3.4. (It works correctly in 2.7). script = """
print(a)
print([a for i in range(5)])
"""
exec(script, globals(), {"a":5}) It produces the following output: 5
Traceback (most recent call last):
File "test.py", line 5, in <module>
exec(script, globals(), {"a":5})
File "<string>", line 3, in <module>
File "<string>", line 3, in <listcomp>
NameError: name 'a' is not defined The variable "a" is getting passed to the script, as expected: printing it out works correctly. But if you use it in a comprehension, the interpreter claims it does not exist. |
exec is subtle. See the explanation linked from bpo-23087, which while not *exactly* on point explains the underlying problem (a comprehension is a new scope, and exec can't reach an intermediate scope the way a compiled function can). As far as the difference from 2.7 goes, the scoping rules for comprehensions changed in python3: the variable you are concerned with is now part of the local scope. |
I don't believe that explanation is correct. You can just as easily get the same problem without explicitly passing a map to exec(). For example: def f():
script = """
print(a)
print([a for i in range(5)])
"""
a = 5
exec(script)
f() The documentation for exec() states, "In all cases, if the optional parts are omitted, the code is executed in the current scope." Therefore the code above should be exactly equivalent to the following: def f():
a = 5
print(a)
print([a for i in range(5)])
f() But the latter works and the former doesn't. Contrary to the documentation, the code is clearly not being executed in the same scope. |
Yes it is. The comprehension is a *new* scope, within the outer scope of the exec, and it *cannot see* the variables in the outer scope of the exec. You have the same problem if you try to use a comprehension in that way in a class statement at the class level. An exec is explicitly *not* equivalent to a function body. It is equivalent to operating in a class body, if you give it two namespaces, and in a global context if you give it one. This is documented. Please don't reopen the issue. |
Then fix the documentation. This behavior directly contradicts the documentation of the exec() function. The question is not what scope the comprehension runs in, it's what scope the script runs in. See my third example. A comprehension in the f() function has no problem seeing local variables defined in that function. If the script were running into the same scope as that function, then comprehensions inside the script would also see those variables. They don't, clearly demonstrating that the script does *not* run in the same scope, and contradicting the documentation. |
OK, it looks like what the documentation of exec is missing is the fact that calling exec with no arguments in a non-global is equivalent to calling it with *two* arguments. That is, your "exec(script)" statement is equivalent to "exec(script, globals(), locals())". This is implicit but very much *not* explicit in the current documentation, and should be made explicit. To be sure I'm explaining this fully: the documentation of exec says "If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition". >>> class Foo:
... a = 10
... [a for x in range(5)]
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in Foo
File "<stdin>", line 3, in <listcomp>
NameError: name 'a' is not defined |
Probably there needs to be more clarification of the compilation context. Class definitions support lexical closures, whereas source code passed to exec is compiled at the time of the call, independent of the lexical context. In the following example, the code objects for both the class body and the comprehension can access the free variable "a". In CPython, the class body references the free variable via the LOAD_CLASSDEREF op, and the comprehension uses the LOAD_DEREF op. def f():
a = 5
class C:
print(a)
print([a for i in range(5)])
>>> f()
5
[5, 5, 5, 5, 5]
>>> dis.dis(f.__code__.co_consts[2])
3 0 LOAD_NAME 0 (__name__)
3 STORE_NAME 1 (__module__)
6 LOAD_CONST 0 ('f.<locals>.C')
9 STORE_NAME 2 (__qualname__)
>>> dis.dis(f.__code__.co_consts[2].co_consts[1])
5 0 BUILD_LIST 0
3 LOAD_FAST 0 (.0)
>> 6 FOR_ITER 12 (to 21)
9 STORE_FAST 1 (i)
12 LOAD_DEREF 0 (a)
15 LIST_APPEND 2
18 JUMP_ABSOLUTE 6
>> 21 RETURN_VALUE |
So there are a couple things to clarify here. When the documentation says "if the optional parts are omitted, the code is executed in the current scope", I think it should explicitly state that this is equivalent to calling exec(object, globals(), locals()). This should help to disabuse the reader of any assumption that the compiled code will extend the nested scoping (i.e. lexical closures) of the calling context. When it says that if "exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition", I think this can be misleading. exec() compiles top-level code. It extends module-like execution, allowing globals and locals to differ and defaulting to the current scope. This sharply contrasts to code that's compiled for a |
I just closed #92681 as duplicate of this.
That sounds reasonable to me as well. I'd imagine that change would be a bit less controversial, so it could even happen independently of negotiating the "class definition" phrasing, if need be. |
cc @carljm who is changing this now with PEP 709. |
I think PEP 709 doesn't really change the core of the discussion above (regarding how to more clearly document the behavior of |
(I am currently reviewing issues potentially addressed by the PEP 667 changes in Python 3.13) While there have been several clarifications to the The current wording in the
So for
(the last case is a currently undocumented situation arising from adding keyword argument support to exec and eval in Python 3.13) To reduce duplication, I would also suggest amending the (although it's worth noting that 3.14 may be dropping the |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: