- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想知道 __future__
导入如何与 eval
交互和 exec
(和 compile
,我猜)。
实验(使用 python 2)表明模块级 __future__
导入确实对 eval
和 exec
执行的代码有影响:
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
但是实验只能让你走到这一步。我的问题是:
eval
、exec
和 中禁用模块级 __future__
导入编译
?最佳答案
Code compiled by calls to the built-in functions
exec()
andcompile()
that occur in a moduleM
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/
Feel free to skip straight to TL/DR if you're not interested in details of the question 简短的序言: 我最近决定
我一直在阅读 A Tour of Go学习Go-Lang到目前为止一切顺利。 我目前在 Struct Fields类(class),这是右侧的示例代码: package main import "fm
Last time I got confused顺便说一下PowerShell急切地展开集合,基思总结了它的启发式如下: Putting the results (an array) within a
我是一名优秀的程序员,十分优秀!