gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:04:51 24 4
gpt4 key购买 nike

我想知道 __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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com