Chain dynamic iterable of context managers to a single with statement

前端 未结 2 971
猫巷女王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:51

    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)
    

提交回复
热议问题