list comprehension in exec with empty locals: NameError

前端 未结 5 1202
清歌不尽
清歌不尽 2020-12-15 22:55

Consider the following snippet:

def bar():
    return 1
print([bar() for _ in range(5)])

It gives an expected output [1, 1, 1, 1, 1]<

5条回答
  •  暖寄归人
    2020-12-15 23:25

    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() and eval() are special in the context of name resolution. ...

    And then in 4.2.4 Interaction with dynamic features:

    The eval() and exec() 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] The exec() and eval() 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.

提交回复
热议问题