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

4
  • You need to somehow elaborate your multiple with objects - the same objects, how many? Commented Oct 2, 2019 at 10:41
  • It's not a duplicate since I require it to be a single object Commented Oct 2, 2019 at 10:47
  • do you expect param=... to always be static (1,2)? Commented Oct 2, 2019 at 10:49
  • I can work with that if it's possible like that Commented Oct 2, 2019 at 10:51

1 Answer 1

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)]]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.