Python eval and exec difference in usage

Python, eval, exec these two functions with similar input parameter types and execution, it often appears confused in usage, as well as frequently wrong, the program is easy to throw an error. The following mainly using the syntax of these two functions to illustrate the difference, and further illustrated with an example.

First, look at the official documentation of these two functions Description:

(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.

Pay particular attention to the bold, found that although the eval and exec first input parameter is string, but eval is an expression, and the exec is a statement, so the problem of distinguishing these two functions are transformed into what it is expression, what is the problem statement, the two concepts must be clear, in order to clear rationale usage of these two functions.

Python, there are expressions such as size comparison, multiply the number list slice, function calls, and so on, and the declaration is rather special, there are assignment statement, expression statement (call function, instance method etc), print statement, if statement, for statement, while statement, def statement, try statement ...

Notes the existence of certain expressions and statements intersection, such as a function call, an instance method calls, print, etc., so for these intersections, can pass these two functions, and in addition, the best expression of incoming eval, the statement incoming exec, otherwise, either thrown or can not achieve the set goals.

Next explained by examples.

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

Guess you like

Origin www.cnblogs.com/johnyang/p/12333899.html