I am trying to implement a class which uses a context manager.
Although I understand the general concept of __enter__
and __exit__
, I don't see how to use the same context manager across multiple code blocks.
For example:
@contextmanager
def backup_context(input)
try:
return xyz
finally:
revert(xyz)
class DoSomething:
def __init__(self):
self.context = context_val
def do_resource_operation_1():
with backup_context(self.context) as context:
do_what_you_want_1(context)
def do_resource_operation_2():
with backup_context(self.context) as context:
do_what_you_want_2(context)
I am invoking the context managers twice. I want to do only once during __init__
and use the same context manager object to do all my operations and then finally when the object is deleted I want to do the revert operation. How should i go about it?
Should I call __enter__
and __exit__
manually instead of using the with
statement?