Why does Python 3 exec() fail when specifying locals?

后端 未结 1 1714
离开以前
离开以前 2020-12-11 15:42

The following executes without an error in Python 3:

code = \"\"\"
import math

def func(x):
    return math.sin(x)

func(10)
\"\"\"
_globals = {}
exec(code,         


        
1条回答
  •  臣服心动
    2020-12-11 16:08

    From the exec() documentation:

    Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

    You passed in two separate dictionaries, but tried to execute code that requires module-scope globals to be available. import math in a class would produce a local scope attribute, and the function you create won't be able to access that as class scope names are not considered for function closures.

    See Naming and binding in the Python execution model reference:

    Class definition blocks and arguments to exec() and eval() are special in the context of name resolution. A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. The namespace of the class definition becomes the attribute dictionary of the class. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods[.]

    You can reproduce the error by trying to execute the code in a class definition:

    >>> class Demo:
    ...     import math
    ...     def func(x):
    ...         return math.sin(x)
    ...     func(10)
    ...
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 5, in Demo
      File "", line 4, in func
    NameError: name 'math' is not defined
    

    Just pass in one dictionary.

    0 讨论(0)
提交回复
热议问题