Chain dynamic iterable of context managers to a single with statement

前端 未结 2 973
猫巷女王i
猫巷女王i 2021-01-21 01:11

I have a bunch of context managers that I want to chain. On the first glance, contextlib.nested looked like a fitting solution. However, this method is flagged as d

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-21 01:41

    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.

提交回复
热议问题