Chain dynamic iterable of context managers to a single with statement

馋奶兔 提交于 2019-12-01 22:18:01

You misunderstood that line. The with statement takes more than one context manager, separated by commas, but not an iterable:

with foo, bar:

works.

Use a contextlib.ExitStack() object if you need to support a dynamic set of context managers:

from contextlib import ExitStack

with ExitStack() as stack:
    for cm in (foo, bar):
        stack.enter_context(cm)

The "multiple manager form of the with statement", as shown in the statement's documentation, would be:

with foo, bar:

i.e. it doesn't support a dynamic number of managers. As the documentation for contextlib.nested notes:

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 this function or else use this function as a model for an application specific implementation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!