gpt4 book ai didi

python - 如果在 "yield" block 内完成, "with"-ing 是否会触发 __exit__ 函数?

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:57 25 4
gpt4 key购买 nike

This question as been asked with respect to returningwith block 内部,但是屈服怎么样?

block 的 __exit__ 是否在 yield 上被调用,然后如果函数下次被调用,__enter__ 是否被再次调用?还是等待生成器退出 with block (或返回)

举个例子:

def tmp_csv_file():
tmp_path = 'tmp.csv'
with open(tmp_path, 'w+') as csv_file:
yield csv_file # will this close the file?
os.remove(tmp_path)

最佳答案

这取决于:

  • 如果您的生成器函数超出范围(或以其他方式被删除),则调用 __exit__

  • 如果生成器耗尽,则调用 __exit__

=> 只要生成器在 with block 中且未耗尽并且保存生成器的变量未被删除,则不会调用 __exit__

例如:

class Test(object):
def __init__(self):
print('init')

def __enter__(self):
print('enter')

def __exit__(self, *args, **kwargs):
print('exit')


def funfunc():
with Test():
yield 1
yield 2

测试它:

>>> a = funfunc()
>>> next(a) # no exit
init
enter
1
>>> next(a) # no exit
2
>>> next(a, 0) # exit because generator leaves the with-context inside the function
exit
0

或者如果手动删除:

>>> a = funfunc()
>>> next(a)
init
enter
1
>>> del a # exit because the variable holding the suspended generator is deleted.
exit

关于python - 如果在 "yield" block 内完成, "with"-ing 是否会触发 __exit__ 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42258514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com