Python: eval() v.s. exec() v.s. compile()

阅读 stackoverflow 上的问题: What's the difference between eval, exec, and compile in Python?

做一下小的总结:

  • eval() 接受 expression, 并返回其结果

  • exec() 接受statements, 返回值为 None

  • compile(): Compile the source into a code or AST object. Code objects can be executed by exec() or eval().

If a str/unicode/bytes containing source code was passed to exec, it behaves equivalently to:

exec(compile(source, '', 'exec'))

and eval similarly behaves equivalent to:

eval(compile(source, '', 'eval'))

参考

python documentation: Built-in Functions

你可能感兴趣的:(Python: eval() v.s. exec() v.s. compile())