python - eval 和 exec 究竟如何与 __future__ 交互?

标签 python eval

我想知道 __future__ 导入如何与 eval 交互和 exec (和 compile,我猜)。

实验(使用 python 2)表明模块级 __future__ 导入确实对 evalexec 执行的代码有影响:

from __future__ import print_function

print(1, end='!\n')
eval(r"print(2, end='!\n')")
exec r"print(3, end='!\n')"

输出:

1!
2!
3!

但与此同时,使用 exec 执行的代码可以执行其自己的 __future__ 导入,只会影响本地代码:

print 1
exec r"from __future__ import print_function; print(2, end='!\n')"
print 3
exec r"print 4"

输出:

1
2!
3
4

但是实验只能让你走到这一步。我的问题是:

  • 这些交互是否明确定义并记录在案?
  • 有没有办法在 evalexec禁用模块级 __future__ 导入编译?

最佳答案

根据 the language reference :

Code compiled by calls to the built-in functions exec() and compile() that occur in a module M containing a future statement will, by default, use the new syntax or semantics associated with the future statement.

您可以在 compile 中禁用此行为:

The optional arguments flags and dont_inherit control which future statements (see PEP 236) affect the compilation of source.

例如:

>>> from __future__ import print_function
>>> print('foo', 'bar')
foo bar
>>> code1 = compile("print('foo', 'bar')", "<string>", "exec")
>>> exec(code1)
foo bar
>>> code2 = compile("print('foo', 'bar')", "<string>", "exec", dont_inherit=True)
>>> exec(code2)
('foo', 'bar')

反过来,据我所知,在正在执行/编译的任意代码中禁用 __future__ 导入是不可能的。

关于python - eval 和 exec 究竟如何与 __future__ 交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50074956/

相关文章:

python - 如何在 Windows 中使用 Popen 调用外部 .py 脚本并等待其完成

python - 将字节数组转换为字符串并返回

python - 在单个 Django 模板上显示来自 2 个模型的内容

javascript - 替代 eval() 以使用 LiveValidation 构造函数

go - 评估/执行 Golang 代码/表达式,如 js 的 eval()

VBScript 执行不适用于变量,但适用于字符串

python - 如何使用 selenium 驱动程序 python 单击覆盖层中的第一个链接

javascript - 安全地使用 eval 将变量用作对象名称

asp.net - <%# Eval ("State") %> 或 <%# DataBinder.Eval(Container.DataItem, "state")%>

python - 在 Flask 部署中 Web 服务器有什么用?