Python 在exec内部导入的print_函数不会影响以后的代码
(Python 2.7)通常,当我执行Python语句时,全局dict在执行后处于更新状态。例如,在下面的代码中,Python 在exec内部导入的print_函数不会影响以后的代码,python,exec,Python,Exec,(Python 2.7)通常,当我执行Python语句时,全局dict在执行后处于更新状态。例如,在下面的代码中,numpy将在执行后以全局形式显示,我可以继续使用它。但是,print\u功能的行为不同。针对locals和globals的成员资格测试都失败了,但我可以看到它并使用它,并且print仍然像python2print语句一样工作。这不一定是我想避免的,但我想了解更多。为什么会这样 exec(""" from __future__ import print_function import
numpy
将在执行后以全局形式显示,我可以继续使用它。但是,print\u功能的行为不同。针对locals
和globals
的成员资格测试都失败了,但我可以看到它并使用它,并且print仍然像python2print语句一样工作。这不一定是我想避免的,但我想了解更多。为什么会这样
exec("""
from __future__ import print_function
import numpy
# prints "haha hoho"
print("haha", "hoho")
""")
# Executes without an error.
print(numpy.zeros((2, 2)))
# Prints "('haha', 'hoho')". (why?)
print("haha", "hoho")
# No error. (why?)
print 'haha'
# Both print False.
print(print_function in globals())
print(print_function in locals())
# However, this prints without an error.
print(print_function)
更新:
我犯了一个错误,会员资格测试应该使用以下名称:
# Now both print True
print("print_function" in globals())
print("print_function" in locals())
将来的导入结果是一个特殊的future语句,这导致编译(在执行exec
语句时)生成不同的代码。因此,它只影响由相应的exec
语句编译的代码的执行
更新:
事实证明,在交互式解释器中,例如笔记本的单元格,future语句的效果超出了单元格边界。但是,如果单元格中存在exec
语句,则exec
中的未来语句仍然只影响要执行的代码