1

I've got some old code from py2.6 that looks like this:

context_managers = [manager_a, manager_b, manager_c]

... stuff

with contextlib.nested(*context_managers):
    ... stuff in context

... more stuff out of context

with contextlib.nested(*context_managers):
    ... separate stuff in context

(If you are curious, this is unittest stuff where I have a list of mock patches that I use for multiple test cases)

Now that I have upgraded to py2.7, I want to remove references to contextlib.nested as it is deprecated and will be no longer available once I upgrade to py3.x. It looks like python 3.x's contextlib.ExitStack does what I need, but that is not available in python 2.7. What is the best option that works for both python 2.7 and python 3.x?

In short, I want to do the following:

  1. Define multiple context managers in a list
  2. Reference that list multiple times in multiple different with statements.

Edit: This has been marked as a duplicate of this question, suggesting I use contextlib2.ExitStack. This is a great solution, but I can't use any outside libraries, so I am editing this question to ask for a built-in python solution that does not require the use of an external library

C_Z_
  • 7,427
  • 5
  • 44
  • 81

0 Answers0