eval,exec和compile有什么区别? [英] What's the difference between eval, exec, and compile?
问题描述
我一直在研究Python代码的动态评估,并遇到了 eval()
和 compile()
函数和 exec
语句。
有人可以解释一下之间的区别eval
和 exec
,以及 compile()
的不同模式如何适应? / p>
简短答案或TL; DR
基本上,<使用了href = https://docs.python.org/3/library/functions.html#eval rel = noreferrer> eval
评估创建一个动态生成的Python表达式,然后 code> exec 用于 exec 动态生成的Python代码,仅出于其副作用。
eval
和 exec
有以下两个区别:
-
eval
仅接受单个表达式,exec
可以采用具有Python语句的代码块:循环,try:除外:
,类
和函数/方法def
初始化等等。
Python中的表达式就是变量赋值的形式:
a_variable =(您可以在这些括号中放入的任何内容都是表达式)
-
eval
返回给定表达式的值,而exec
忽略返回值从其代码开始,并始终返回None
(在Python 2中,这是一条语句,不能用作表达式,因此它实际上不返回任何内容)。
在版本1.0-2.7中, exec
是一个声明,因为CPython需要为使用 exec
在函数内部产生副作用的函数生成另一种代码对象。
在Python 3中, exec
是一个函数;
因此,基本上:
>> a = 5
>> eval(’37 + a’)#它是一个表达式
42
>>> exec(’37 + a’)#这是一个表达式语句;值将被忽略(不返回任何值)
>> exec(’a = 47’)#修改全局变量作为副作用
>>> a
47
>> eval(’a = 47’)#您无法评估语句
回溯(最近一次调用为最新):
文件< stdin>,< module>中的第1行
文件< string>,第1行
a = 47
^
SyntaxError:语法无效
'exec'中的
编译
模式将任意数量的语句编译为字节码,该字节码始终隐式返回 None
,而在'eval'
模式,它将一个单个表达式编译为字节码,该字节码返回该表达式的值。
>> eval(compile(‘42’,‘< string>’,‘exec’))#代码返回None
>>> eval(compile('42','< string>','eval'))#代码返回42
42
>> exec(compile('42','< string>','eval'))#代码返回42,
>>> #但被执行程序
忽略
在'eval'
模式(如果传入了字符串,则使用 eval
函数),如果 compile
引发异常源代码中包含语句或除单个表达式之外的其他任何内容:
>> compile('for i in range(3):print(i)','< string>','eval')
追溯(最近一次调用为最后):
文件< stdin> ,<模块>中的第1行
文件< string>,第1行
for range(3)中的i:print(i)
^
SyntaxError:语法无效
实际上,语句 eval只接受一个表达式 仅在将字符串(包含Python 源代码)传递给 eval
时适用。然后使用 compile(source,' < string>','eval')
这才是真正的区别所在。
如果 code
对象(包含Python bytecode )传递给 exec
或 eval
,它们的行为相同,除了 exec
忽略返回值而仍然返回无
总是。因此,有可能使用 eval
执行具有语句的内容,如果您只是 compile
d之前将其转换为字节码而不是将其作为字符串传递:
>> eval(compile(’if 1:print( Hello)',‘< string>’,‘exec’))
Hello
>>
可以正常工作,即使已编译的代码包含语句。它仍然返回 None
,因为那是从 compile
返回的代码对象的返回值。
在'eval'
模式下(如果使用 eval
传入一个字符串),如果源代码包含除单个表达式之外的语句或其他任何内容,编译
会引发异常:
>> compile('for i in range(3):print(i)','< string>'。'eval')
追溯(最近一次调用为最后):
文件< stdin> ,<模块>中的第1行
文件< string>,第1行
for range(3)中的i:print(i)
^
SyntaxError:语法无效
更长的答案,又称血腥细节
exec
和 eval
exec
函数(该函数为 Python 2中的语句)用于执行动态创建的语句或程序:
>>程序=’’
代表范围(3)中的i:
打印( Python很酷)
’’
>>> exec(program)
Python很酷
Python很酷
Python很酷
>>>
>> a = 2
>> my_calculation = ‘42 * a’
>>>结果= eval(my_calculation)
>>结果
84
exec
和 eval
都接受将程序/表达式作为 str
, unicode运行
或 bytes
对象包含源代码,或作为 code
对象其中包含Python字节码。
如果 str
/ unicode
/ <$ c包含源代码的$ c> bytes 传递给 exec
,它的行为等效于:
exec(compile(source,'< string>','exec'))
和 eval
类似地等效于:
eval(compile(source,'< string>','eval'))
由于所有表达式都可以用作Python中的语句(在Python exec
(如果不需要返回值)。也就是说,您可以使用 eval('my_func(42)')
或 exec('my_func(42)')
,区别在于 eval
返回 my_func
和返回的值exec
丢弃它:
>> def my_func(arg):
... print(用%d调用%arg)
... return arg * 2
...
> > exec(’my_func(42)’)
用42
>>>调用eval(’my_func(42)’)
用42
84
>>调用
在2个中,只有 exec
接受源包含语句的代码,例如 def
, for
, while
, import
或 class
赋值语句(又名 a = 42
)或整个程序:
>> exec(’for i in range(3):print(i)’)
0
1
2
>> eval(’表示范围(3)中的i:print(i)’)
追溯(最近一次调用):
文件< stdin>,在< module>中的第1行
文件< string>,第1行
for range(3)中的i:print(i)
^
SyntaxError:语法无效
两个 exec
和 eval
接受另外两个位置参数- globals
和 locals
-是代码看到的全局和局部变量作用域。这些默认为 exec <的范围内的
globals()
和 locals()
/ code>或 eval
,但任何词典都可用于 globals
和任何映射
用于
当地人
(当然包括 dict
)。这些不仅可以用于限制/修改代码中看到的变量,而且还经常用于捕获 exec
uted代码创建的变量:
>> g = dict()
>> l = dict()
>> exec(‘global a; a,b = 123,42’,g,l)
>> g [’a’]
123
>>> l
{'b':42}
(如果显示整个值 g
,则要长得多,因为 exec
和 eval
将内置模块作为 __ builtins __
自动添加到全局变量中)。
在Python 2中, exec
语句的正式语法实际上是 exec代码在全局变量,本地变量
中,如
>> exec’global a; a,b = 123,42'in g,l
但是可选语法 exec(代码,全局变量,本地变量)
也一直被接受(见下文)。
编译
compile(源,文件名,模式,标志= 0,dont_inherit = False,optimize = -1)
内置可用于加快重复速度通过将源代码编译为代码,使用
对象。 exec
或 eval
调用同一代码 mode
参数控制 compile
函数接受的代码片段的类型以及它产生的字节码的类型。选项为'eval'
,'exec'
和'single'
:
-
'eval'
模式需要单个表达式,并将生成字节码,该字节码在运行时将返回该表达式的值:>> ;> dis.dis(compile('a + b','< string>','eval'))
1 0 LOAD_NAME 0(a)
3 LOAD_NAME 1(b)
6 BINARY_ADD
7 RETURN_VALUE
-
'exec'
接受从单个表达式到整个代码模块的任何种类的python构造,并像将其作为模块顶级语句一样执行它们。代码对象返回None
:>> dis.dis(compile('a + b','< string>','exec'))
1 0 LOAD_NAME 0(a)
3 LOAD_NAME 1(b)
6 BINARY_ADD
7 POP_TOP<-丢弃结果
8 LOAD_CONST 0(无)<-在堆栈
上不加载11 RETURN_VALUE<-返回堆栈
顶 -
'single'
是'exec'
接受包含单语句(或多个由;
分隔的语句)的源代码,如果最后一个语句是一个表达式语句,生成的字节码还会将该表达式的值的repr
打印到标准输出(!)。 p>
<< c $ c> if -
elif
-else
链,包含else
的循环,以及try
及其除了
,else
和finally
块被视为单个语句。
源片段包含2个顶级语句是
'single'
的错误,除了在Python 2中存在一个一个错误,该错误有时会在其中允许多个顶级语句代码;只有第一个被编译;其余的将被忽略:
在Python 2.7.8中:
>>> exec(compile(‘a = 5\na = 6’,‘< string>’,‘单’))
>>> a
5
在Python 3.4.2中:
>> exec(compile('a = 5\na = 6','< string>','single'))
时发现多个语句
追溯(最近一次调用为最后):
文件< stdin>在< module>中的第1行
文件< string>,第1行
a = 5
^
SyntaxError:在编译单个语句
这对于制作交互式Python shell非常有用。但是,即使您
eval
生成的代码,该表达式的值也不会返回 。
因此, exec
和 eval
的最大区别来自 compile
函数及其模式。
要将源代码编译为字节码, compile
支持编译 抽象语法树 (Python代码的解析树)到 code
对象中;并将源代码转换成抽象语法树( ast.parse
用Python编写,仅调用 compile(source,filename,mode,PyCF_ONLY_AST)
);这些用于例如动态修改源代码,以及用于动态代码创建,因为在复杂情况下,将代码作为节点树而不是文本行来处理通常会更容易。
虽然 eval
仅允许您评估包含单个表达式的字符串,但您可以 eval
整个语句,甚至是已经被编译
d到字节码中的整个模块;也就是说,在Python 2中, print
是一条语句,不能直接由 eval
引导:
>> eval('for i in range(3):print( Python is cool)')
追溯(最近一次调用为最新):
文件< stdin>,第1行,在< ; module>
文件< string>,行1
for range(3)中的i:print( Python is cool)
^
SyntaxError:语法无效
编译
用'exec '
模式转换为 code
对象,您可以 eval
它; eval
函数将返回 None
。
>>代码=编译(对于范围3中的i:print( Python很酷)),
foo.py, exec)
>>> eval(code)
Python很酷
Python很酷
Python很酷
如果有人查看 eval
和 <$ c CPython 3中的$ c> exec 源代码,这非常明显;他们都使用相同的参数调用 PyEval_EvalCode
,唯一的区别是 exec
显式返回 None
。
Python 2和Python 3之间 exec
的语法差异
一个Python 2 的主要区别在于, exec
是一个语句,而 eval
是一个语句。内置函数(均为Python 3中的内置函数)。
是众所周知的事实,Python 2中 exec
的正式语法是 exec代码[在globals [,locals]]
。
与大多数Python 2到3 移植 指南 似乎 来建议,CPython 2中的 exec
语句也可以与语法一起使用看上去 完全,就像Python 3中的 exec
函数调用一样。原因是Python 0.9.9具有 exec(代码,全局变量,本地变量)
内置函数!而该内置函数被 exec
语句在Python 1.0发布之前的某个地方。
由于希望不破坏与Python 0.9.9的向后兼容性,因此 Guido van Rossum在1993年添加了一个兼容性hack :如果 code
是长度为2或3的元组,并且是 globals
和 locals
不会传递给 exec
语句,否则,代码
将被解释为元组分别是 globals
和 locals
。即使在 Python 1.4文档(在线上最早的可用版本)中也没有提到兼容性黑客);因此对于移植指南和工具的许多作者并不了解,直到它被记录再次在2012年11月:
第一个表达式也可以是长度为2或3的元组。在这种情况下,必须省略可选部分。格式
exec(expr,globals)
等效于exec expr in globals
,而格式exec(expr,globals,locals)
等效于exec expr in globals,locals
。exec
的元组形式提供了与Python 3的兼容性,其中exec
是函数而不是语句。
是的,在CPython 2.7中,它被方便地称为前向兼容选项(为什么使人们感到困惑,因为存在向后兼容选项),而实际上
已经存在了20年以实现向后兼容。
因此而 exec
是Python 1和Python 2中的语句,也是Python 3和Python 0.9.9中的内置函数,
>> exec( print(a),globals(),{'a':42})
42
在可能的每个广泛发行的Python版本中都具有相同的行为;并且也可以在Jython 2.5.2,PyPy 2.3.1(Python 2.7.6)和IronPython 2.6.1中使用(对CPython的未记录的行为表示严格的敬意)。
您无法在Pythons 1.0-2.7中使用其兼容性技巧,将 exec
的返回值存储到变量中:
Python 2.7.11+(默认,2016年4月17日,14:00:29)
在Linux2
上[GCC 5.3.1 20160413]键入帮助,版权,信用或许可证以获取更多信息。
>> a = exec('print(42)')
文件< stdin>,第1行
a = exec('print(42)')
^
语法错误:无效语法
(在Python 3中也没有用,如 exec
始终返回 None
),或将引用传递给 exec
:
>> call_later(exec,'print(42)',delay = 1000)
文件< stdin>,第1行
call_later(exec,'print(42)',delay = 1000)
^
SyntaxError:语法无效
某些人可能实际使用过的模式,虽然不太可能
或在列表理解中使用它:
>> ;> [[print(42)'中的i的exec(i),'print(foo)']
文件< stdin>,第1行
[[i中的i的exec(i) 'print(42)','print(foo)']
^
SyntaxError:语法无效
滥用列表推导(改为使用 for
循环!)。
I've been looking at dynamic evaluation of Python code, and come across the eval()
and compile()
functions, and the exec
statement.
Can someone please explain the difference between eval
and exec
, and how the different modes of compile()
fit in?
The short answer, or TL;DR
Basically, eval
is used to evaluate a single dynamically generated Python expression, and exec
is used to execute dynamically generated Python code only for its side effects.
eval
and exec
have these two differences:
eval
accepts only a single expression,exec
can take a code block that has Python statements: loops,try: except:
,class
and function/methoddef
initions and so on.An expression in Python is whatever you can have as the value in a variable assignment:
a_variable = (anything you can put within these parentheses is an expression)
eval
returns the value of the given expression, whereasexec
ignores the return value from its code, and always returnsNone
(in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).
In versions 1.0 - 2.7, exec
was a statement, because CPython needed to produce a different kind of code object for functions that used exec
for its side effects inside the function.
In Python 3, exec
is a function; its use has no effect on the compiled bytecode of the function where it is used.
Thus basically:
>>> a = 5
>>> eval('37 + a') # it is an expression
42
>>> exec('37 + a') # it is an expression statement; value is ignored (None is returned)
>>> exec('a = 47') # modify a global variable as a side effect
>>> a
47
>>> eval('a = 47') # you cannot evaluate a statement
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
a = 47
^
SyntaxError: invalid syntax
The compile
in 'exec'
mode compiles any number of statements into a bytecode that implicitly always returns None
, whereas in 'eval'
mode it compiles a single expression into bytecode that returns the value of that expression.
>>> eval(compile('42', '<string>', 'exec')) # code returns None
>>> eval(compile('42', '<string>', 'eval')) # code returns 42
42
>>> exec(compile('42', '<string>', 'eval')) # code returns 42,
>>> # but ignored by exec
In the 'eval'
mode (and thus with the eval
function if a string is passed in), the compile
raises an exception if the source code contains statements or anything else beyond a single expression:
>>> compile('for i in range(3): print(i)', '<string>', 'eval')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(3): print(i)
^
SyntaxError: invalid syntax
Actually the statement "eval accepts only a single expression" applies only when a string (which contains Python source code) is passed to eval
. Then it is internally compiled to bytecode using compile(source, '<string>', 'eval')
This is where the difference really comes from.
If a code
object (which contains Python bytecode) is passed to exec
or eval
, they behave identically, excepting for the fact that exec
ignores the return value, still returning None
always. So it is possible use eval
to execute something that has statements, if you just compile
d it into bytecode before instead of passing it as a string:
>>> eval(compile('if 1: print("Hello")', '<string>', 'exec'))
Hello
>>>
works without problems, even though the compiled code contains statements. It still returns None
, because that is the return value of the code object returned from compile
.
In the 'eval'
mode (and thus with the eval
function if a string is passed in), the compile
raises an exception if the source code contains statements or anything else beyond a single expression:
>>> compile('for i in range(3): print(i)', '<string>'. 'eval')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(3): print(i)
^
SyntaxError: invalid syntax
The longer answer, a.k.a the gory details
exec
and eval
The exec
function (which was a statement in Python 2) is used for executing a dynamically created statement or program:
>>> program = '''
for i in range(3):
print("Python is cool")
'''
>>> exec(program)
Python is cool
Python is cool
Python is cool
>>>
The eval
function does the same for a single expression, and returns the value of the expression:
>>> a = 2
>>> my_calculation = '42 * a'
>>> result = eval(my_calculation)
>>> result
84
exec
and eval
both accept the program/expression to be run either as a str
, unicode
or bytes
object containing source code, or as a code
object which contains Python bytecode.
If a str
/unicode
/bytes
containing source code was passed to exec
, it behaves equivalently to:
exec(compile(source, '<string>', 'exec'))
and eval
similarly behaves equivalent to:
eval(compile(source, '<string>', 'eval'))
Since all expressions can be used as statements in Python (these are called the Expr
nodes in the Python abstract grammar; the opposite is not true), you can always use exec
if you do not need the return value. That is to say, you can use either eval('my_func(42)')
or exec('my_func(42)')
, the difference being that eval
returns the value returned by my_func
, and exec
discards it:
>>> def my_func(arg):
... print("Called with %d" % arg)
... return arg * 2
...
>>> exec('my_func(42)')
Called with 42
>>> eval('my_func(42)')
Called with 42
84
>>>
Of the 2, only exec
accepts source code that contains statements, like def
, for
, while
, import
, or class
, the assignment statement (a.k.a a = 42
), or entire programs:
>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(3): print(i)
^
SyntaxError: invalid syntax
Both exec
and eval
accept 2 additional positional arguments - globals
and locals
- which are the global and local variable scopes that the code sees. These default to the globals()
and locals()
within the scope that called exec
or eval
, but any dictionary can be used for globals
and any mapping
for locals
(including dict
of course). These can be used not only to restrict/modify the variables that the code sees, but are often also used for capturing the variables that the exec
uted code creates:
>>> g = dict()
>>> l = dict()
>>> exec('global a; a, b = 123, 42', g, l)
>>> g['a']
123
>>> l
{'b': 42}
(If you display the value of the entire g
, it would be much longer, because exec
and eval
add the built-ins module as __builtins__
to the globals automatically if it is missing).
In Python 2, the official syntax for the exec
statement is actually exec code in globals, locals
, as in
>>> exec 'global a; a, b = 123, 42' in g, l
However the alternate syntax exec(code, globals, locals)
has always been accepted too (see below).
compile
The compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
built-in can be used to speed up repeated invocations of the same code with exec
or eval
by compiling the source into a code
object beforehand. The mode
parameter controls the kind of code fragment the compile
function accepts and the kind of bytecode it produces. The choices are 'eval'
, 'exec'
and 'single'
:
'eval'
mode expects a single expression, and will produce bytecode that when run will return the value of that expression:>>> dis.dis(compile('a + b', '<string>', 'eval')) 1 0 LOAD_NAME 0 (a) 3 LOAD_NAME 1 (b) 6 BINARY_ADD 7 RETURN_VALUE
'exec'
accepts any kinds of python constructs from single expressions to whole modules of code, and executes them as if they were module top-level statements. The code object returnsNone
:>>> dis.dis(compile('a + b', '<string>', 'exec')) 1 0 LOAD_NAME 0 (a) 3 LOAD_NAME 1 (b) 6 BINARY_ADD 7 POP_TOP <- discard result 8 LOAD_CONST 0 (None) <- load None on stack 11 RETURN_VALUE <- return top of stack
'single'
is a limited form of'exec'
which accepts a source code containing a single statement (or multiple statements separated by;
) if the last statement is an expression statement, the resulting bytecode also prints therepr
of the value of that expression to the standard output(!).An
if
-elif
-else
chain, a loop withelse
, andtry
with itsexcept
,else
andfinally
blocks is considered a single statement.A source fragment containing 2 top-level statements is an error for the
'single'
, except in Python 2 there is a bug that sometimes allows multiple toplevel statements in the code; only the first is compiled; the rest are ignored:In Python 2.7.8:
>>> exec(compile('a = 5\na = 6', '<string>', 'single')) >>> a 5
And in Python 3.4.2:
>>> exec(compile('a = 5\na = 6', '<string>', 'single')) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1 a = 5 ^ SyntaxError: multiple statements found while compiling a single statement
This is very useful for making interactive Python shells. However, the value of the expression is not returned, even if you
eval
the resulting code.
Thus greatest distinction of exec
and eval
actually comes from the compile
function and its modes.
In addition to compiling source code to bytecode, compile
supports compiling abstract syntax trees (parse trees of Python code) into code
objects; and source code into abstract syntax trees (the ast.parse
is written in Python and just calls compile(source, filename, mode, PyCF_ONLY_AST)
); these are used for example for modifying source code on the fly, and also for dynamic code creation, as it is often easier to handle the code as a tree of nodes instead of lines of text in complex cases.
While eval
only allows you to evaluate a string that contains a single expression, you can eval
a whole statement, or even a whole module that has been compile
d into bytecode; that is, with Python 2, print
is a statement, and cannot be eval
led directly:
>>> eval('for i in range(3): print("Python is cool")')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for i in range(3): print("Python is cool")
^
SyntaxError: invalid syntax
compile
it with 'exec'
mode into a code
object and you can eval
it; the eval
function will return None
.
>>> code = compile('for i in range(3): print("Python is cool")',
'foo.py', 'exec')
>>> eval(code)
Python is cool
Python is cool
Python is cool
If one looks into eval
and exec
source code in CPython 3, this is very evident; they both call PyEval_EvalCode
with same arguments, the only difference being that exec
explicitly returns None
.
Syntax differences of exec
between Python 2 and Python 3
One of the major differences in Python 2 is that exec
is a statement and eval
is a built-in function (both are built-in functions in Python 3).
It is a well-known fact that the official syntax of exec
in Python 2 is exec code [in globals[, locals]]
.
Unlike majority of the Python 2-to-3 porting guides seem to suggest, the exec
statement in CPython 2 can be also used with syntax that looks exactly like the exec
function invocation in Python 3. The reason is that Python 0.9.9 had the exec(code, globals, locals)
built-in function! And that built-in function was replaced with exec
statement somewhere before Python 1.0 release.
Since it was desirable to not break backwards compatibility with Python 0.9.9, Guido van Rossum added a compatibility hack in 1993: if the code
was a tuple of length 2 or 3, and globals
and locals
were not passed into the exec
statement otherwise, the code
would be interpreted as if the 2nd and 3rd element of the tuple were the globals
and locals
respectively. The compatibility hack was not mentioned even in Python 1.4 documentation (the earliest available version online); and thus was not known to many writers of the porting guides and tools, until it was documented again in November 2012:
The first expression may also be a tuple of length 2 or 3. In this case, the optional parts must be omitted. The form
exec(expr, globals)
is equivalent toexec expr in globals
, while the formexec(expr, globals, locals)
is equivalent toexec expr in globals, locals
. The tuple form ofexec
provides compatibility with Python 3, whereexec
is a function rather than a statement.
Yes, in CPython 2.7 that it is handily referred to as being a forward-compatibility option (why confuse people over that there is a backward compatibility option at all), when it actually had been there for backward-compatibility for two decades.
Thus while exec
is a statement in Python 1 and Python 2, and a built-in function in Python 3 and Python 0.9.9,
>>> exec("print(a)", globals(), {'a': 42})
42
has had identical behaviour in possibly every widely released Python version ever; and works in Jython 2.5.2, PyPy 2.3.1 (Python 2.7.6) and IronPython 2.6.1 too (kudos to them following the undocumented behaviour of CPython closely).
What you cannot do in Pythons 1.0 - 2.7 with its compatibility hack, is to store the return value of exec
into a variable:
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = exec('print(42)')
File "<stdin>", line 1
a = exec('print(42)')
^
SyntaxError: invalid syntax
(which wouldn't be useful in Python 3 either, as exec
always returns None
), or pass a reference to exec
:
>>> call_later(exec, 'print(42)', delay=1000)
File "<stdin>", line 1
call_later(exec, 'print(42)', delay=1000)
^
SyntaxError: invalid syntax
Which a pattern that someone might actually have used, though unlikely;
Or use it in a list comprehension:
>>> [exec(i) for i in ['print(42)', 'print(foo)']
File "<stdin>", line 1
[exec(i) for i in ['print(42)', 'print(foo)']
^
SyntaxError: invalid syntax
which is abuse of list comprehensions (use a for
loop instead!).
这篇关于eval,exec和compile有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!