Python中eval与exec用法的区别

Python中eval,exec这两个函数有着相似的输入参数类型和执行功能,因此在用法上经常出现混淆,以至经常用错,程序易抛出错误。下面主要通过这两个函数的语法来阐述区别,并用例子来进一步说明。

首先看下官方文档对这两个函数的说明:

(1)eval(expr, globals=None, locals=None, /)

Evaluate the given expr in the context of globals and locals.
This call returns the expr result.
The expr may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.

(2)exec(stmts, globals=None, locals=None, /)

Execute the given stmts in the context of globals and locals.

The stmts may be a string representing one or more **Python statements**
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.

特别注意上述黑体字,发现eval与exec的第一个输入参数虽然都是string,但eval中的是表达式,而exec中的是声明,所以区分这两个函数的问题就转化成了什么是表达式,什么是声明的问题,这两个概念必须搞清楚,才能理清楚这两个函数的用法。

Python中,表达式有比如比较大小,数字相乘,列表切片,函数调用等等,而声明则比较特殊,有assignment statement,expression statement(call function,instance method etc),print statement,if statement,for statement,while statement,def statement,try statement...

注意到表达式与声明存在某些交集,如函数调用,实例方法调用,print等,因此对于这些交集,都可以传入这两个函数,而除此之外,最好将expression传入eval,而statement传入exec,否则,要么抛出异常,要么不能实现既定的目标。

接下来用实例来阐述。

eval('x=1')#赋值声明,传入eval报错
  File "<string>", line 1
    x=1
     ^
SyntaxError: invalid syntax
exec('x=1');x
1
eval('1<2')#比较表达式
True
exec('1<2');print('No output')#表达式,没有输出
No output
eval('print("print can be shown via eval")')
print can be shown via eval
exec('print("print can also be shown via exec")')
print can also be shown via exec
posted @ 2020-02-19 23:33  JohnYang819  阅读(531)  评论(0编辑  收藏  举报