【发布时间】:2015-02-19 14:05:32
【问题描述】:
我制作了一个简单的测试程序来测试使用globals()["__debug__"] = value 分配给__debug__ 的功能(__debug__ = value 是SyntaxError)。它基本上试图引发AssertionError 并打印是否引发了错误以及是否预期它。我这样做是因为我遇到了 __debug__ 更改程序中途的问题。
print("__debug__ is", __debug__)
exp = ["(expected)", "(not expected)"]
if __debug__:
exp = exp[::-1]
try:
assert False
print("No AssertionError", exp[0])
except AssertionError:
print("AssertionError", exp[1])
exp = exp[::-1]
globals()["__debug__"] = not __debug__
print("__debug__ is", __debug__)
try:
assert False
print("No AssertionError", exp[0])
except AssertionError:
print("AssertionError", exp[1])
从命令提示符运行时,无论有无 -O 标志,它都会产生意外结果。
C:\Test>python assert.py
__debug__ is True
AssertionError (expected)
__debug__ is False
AssertionError (not expected)
C:\Test>python -O assert.py
__debug__ is False
No AssertionError (expected)
__debug__ is True
No AssertionError (not expected)
似乎__debug__ 正在改变,但assert 实际上并没有检查它是否有。
【问题讨论】: