我有一个上下文装饰器,完成后会产生副作用。我注意到,如果我使用字典理解,就不会出现副作用。
from contextlib import contextmanager
import traceback
import sys
accumulated = []
@contextmanager
def accumulate(s):
try:
yield
finally:
print("Appending %r to accumulated" % s)
accumulated.append(s)
def iterate_and_accumulate(iterable):
for item in iterable:
with accumulate(item):
yield item
def boom_unless_zero(i):
if i > 0:
raise RuntimeError("Boom!")
try:
{i: boom_unless_zero(i) for i in iterate_and_accumulate([0, 1])}
except:
traceback.print_exc()
print(accumulated)
print('\n=====\n')
try:
{i: boom_unless_zero(i) for i in iterate_and_accumulate([0, 1])}
except:
traceback.print_exc()
print(accumulated)
print('Finished!')
Output:
$ python2 boom3.py
Appending 0 to accumulated
Traceback (most recent call last):
File "boom3.py", line 25, in <module>
{i: boom_unless_zero(i) for i in iterate_and_accumulate([0, 1])}
File "boom3.py", line 25, in <dictcomp>
{i: boom_unless_zero(i) for i in iterate_and_accumulate([0, 1])}
File "boom3.py", line 22, in boom_unless_zero
raise RuntimeError("Boom!")
RuntimeError: Boom!
[0]
=====
Appending 0 to accumulated
Appending 1 to accumulated
Traceback (most recent call last):
File "boom3.py", line 34, in <module>
{i: boom_unless_zero(i) for i in iterate_and_accumulate([0, 1])}
File "boom3.py", line 34, in <dictcomp>
{i: boom_unless_zero(i) for i in iterate_and_accumulate([0, 1])}
File "boom3.py", line 22, in boom_unless_zero
raise RuntimeError("Boom!")
RuntimeError: Boom!
[0, 0, 1]
Finished!
Appending 1 to accumulated
奇怪的是,副作用是在我的脚本“完成”后发生的。这意味着如果用户使用字典理解,则无法使用我的 contextdecorator。
我注意到这种行为在 Python 3 上消失了,如果我写的话这种行为也不会发生[boom_unless_zero(i) for i in iterate_and_accumulate([0, 1])]
而不是字典理解。
为什么会出现这种情况?