Skip to content Skip to sidebar Skip to footer

Chain Dynamic Iterable Of Context Managers To A Single With Statement

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 deprecated in the

Solution 1:

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

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

Solution 2:

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.

Post a Comment for "Chain Dynamic Iterable Of Context Managers To A Single With Statement"