Consider the following snippet:
def bar():
return 1
print([bar() for _ in range(5)])
It gives an expected output [1, 1, 1, 1, 1]<
I'm late to the party here, but there is a better documentation reference buried in the execution model.
In section 4.2.2 Resolution of names:
Class definition blocks and arguments to
exec()andeval()are special in the context of name resolution. ...
And then in 4.2.4 Interaction with dynamic features:
The
eval()andexec()functions do not have access to the full environment for resolving names. Names may be resolved in the local and global namespaces of the caller. Free variables are not resolved in the nearest enclosing namespace, but in the global namespace. [1] Theexec()andeval()functions have optional arguments to override the global and local namespace. If only one namespace is specified, it is used for both.
[1] This limitation occurs because the code that is executed by these operations is not available at the time the module is compiled.