exec中导入的print_function不会影响之后的代码

时间:2017-01-08 07:14:00

标签: python exec

(Python 2.7)通常当我exec一个python语句时,全局字典在执行后处于更新状态。例如,在下面的代码中,执行后numpy将在全局变量中,我可以继续使用它。但是,print_function表现不同。针对localsglobals的成员资格测试都失败了,但我可以看到它并使用它,并且打印仍然表现为python 2 print语句。这不一定是我想避免的,但我想更多地了解这一点。为什么会这样?

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())

未来的导入结果是一个特殊的未来声明,它导致编译(执行exec语句时)生成不同的代码。因此,它只影响由相应的exec语句编译的代码的执行。

更新:

事实证明,在交互式解释器中,例如笔记本的单元格,未来语句的效果超出了单元边界。但是,如果单元格中存在exec语句,exec中的未来语句仍然只会影响代码exec'。

0 个答案:

没有答案
相关问题