1

I want to get this behavior:

with Obj(param=1):
    with Obj(param=2):
        print(...)

using a single object:

with UnifyingObj():
    print(...)

I'm wondering how to safely implement the UnifyingObj class

This has to be a single class. I tried to do something like that:

class _DualWith:
    def __init__(self):
        self._with1 = Obj(param=1)
        self._with2 = Obj(param=2)

    def __enter__(self):
        self._with1.__enter__()
        self._with2.__enter__()

    def __exit__(self, *args, **kwargs):
        self._with2.__exit__(*args, **kwargs)
        self._with1.__exit__(*args, **kwargs)

But I don't think it's fully safe

user972014
  • 3,296
  • 6
  • 49
  • 89

1 Answers1

1

Do you NEED to wrap that behavior in a separate class? Maybe you could do something like this?

from contextlib import ExitStack


with ExitStack as stack:
    objects = [stack.enter_context(obj) for obj in [Obj(param=1), Obj(param=2)]]
Paul M.
  • 10,481
  • 2
  • 9
  • 15