编程语言
首页 > 编程语言> > 在“with”中嵌入Python上下文管理器的迭代器

在“with”中嵌入Python上下文管理器的迭代器

作者:互联网

我有一个返回上下文管理器的迭代器.

我想要一个pythonic with语句,它模拟几个嵌套语句的行为,一个用于迭代器返回的每个上下文管理器.

可以说,我想要(不推荐使用)contextlib.nested函数的推广.

解决方法:

docs

Developers that need to support nesting of a variable number of context managers can either use the warnings module to suppress the DeprecationWarning raised by [contextlib.nested] or else use this function as a model for an application specific implementation.

处理多个上下文管理器的困难之处在于它们非常简单地进行交互:例如,您可能首先__enter__然后在第二个__enter__中引发异常.这些边缘情况恰恰是导致嵌套被弃用的原因.如果您想支持它们,您必须非常仔细地考虑如何编写代码.您可能希望阅读PEP-0343的想法.

标签:python,iterator,nested,contextmanager
来源: https://codeday.me/bug/20190626/1292129.html