Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 403
Dejan Avatar asked Feb 28 '26 04:02

Dejan


1 Answers

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
like image 80
Daweo Avatar answered Mar 06 '26 02:03

Daweo