gpt4 book ai didi

python - 如何 __enter__ n 上下文管理器?

转载 作者:太空狗 更新时间:2023-10-30 02:30:27 24 4
gpt4 key购买 nike

使用 with 语句,我们可以仅使用一层缩进/嵌套来输入许多上下文处理程序:

>>> from contextlib import contextmanager
>>> @contextmanager
... def frobnicate(n):
... print('frobbing {}'.format(n))
... yield
...
>>> frob1 = frobnicate(1)
>>> frob2 = frobnicate(2)
>>> with frob1, frob2:
... pass
...
frobbing 1
frobbing 2

但这似乎不起作用:

>>> frobs = [frobnicate(1), frobnicate(2)]
>>> with *frobs:
... pass
# SyntaxError: invalid syntax

我们如何才能输入 n 个上下文管理器而不必手动写出每个上下文管理器?

最佳答案

python2.7 有 contextlib.nested然而,要做到这一点,由于容易出错的怪癖,它已被弃用。

This function has two major quirks that have led to it being deprecated. Firstly, as the context managers are all constructed before the function is invoked, the __new__() and __init__() methods of the inner context managers are not actually covered by the scope of the outer context managers. That means, for example, that using nested() to open two files is a programming error as the first file will not be closed promptly if an exception is thrown when opening the second file.

Secondly, if the __enter__() method of one of the inner context managers raises an exception that is caught and suppressed by the __exit__() method of one of the outer context managers, this construct will raise RuntimeError rather than skipping the body of the with statement.

python3.3 在 contextlib.ExitStack 上做得更好看起来像:

from contextlib import ExitStack

with ExitStack() as stack:
contexts = [stack.enter_context(frobnicate(i)) for i in range(2)]
...

参见 contextlib2用于向后移植到 python2.x 代码。

关于python - 如何 __enter__ n 上下文管理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26855747/

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