Search code examples
pythoncontextmanager

How to dynamically apply multiple with statements


How to generate nested with statements? Example:

with patch.object(getattr("module1", "cls1"), "foo"):
  with patch.object(getattr("module2", "cls2"), "foo"):
    with patch.object(getattr("module3", "cls3"), "foo"):
      # do something

If I have a list of items which needs to be put in the nested with statements, e.g.

list=[("module1", "cls1"), ("module2", "cls2"), ("module3", "cls3")]

how can I simulate the above code?


Solution

  • This looks like task for contextlib.ExitStack, following example is given in docs

    with ExitStack() as stack:
        files = [stack.enter_context(open(fname)) for fname in filenames]
        # All opened files will automatically be closed at the end of
        # the with statement, even if attempts to open files later
        # in the list raise an exception