Skip to content

Instantly share code, notes, and snippets.

@ssanderson
Last active October 12, 2017 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssanderson/8dbebad58b3c2633abede41ae86c3d77 to your computer and use it in GitHub Desktop.
Save ssanderson/8dbebad58b3c2633abede41ae86c3d77 to your computer and use it in GitHub Desktop.
Context manager that wraps another context manager
from __future__ import print_function
from contextlib import contextmanager
@contextmanager
def some_context_manager(x):
print("Entering", x)
yield
print("Exiting", x)
class WrappingContext(object):
def __init__(self, other_cm):
self._other_cm = other_cm
self._current_context = None
def do_setup_stuff(self):
print("Setting Up Wrapper")
def do_teardown_stuff(self):
print("Tearing Down Wrapper")
@contextmanager
def _make_context(self):
self.do_setup_stuff()
try:
with self._other_cm:
yield
finally:
self.do_teardown_stuff()
def __enter__(self):
self._current_context = self._make_context()
self._current_context.__enter__()
return self
def __exit__(self, *exc_info):
assert self._current_context is not None, "Exited too many times!"
return self._current_context.__exit__(*exc_info)
other_cm = some_context_manager('foo')
with WrappingContext(other_cm) as cm:
print("In the with block")
# Prints:
# Setting Up Wrapper
# Entering foo
# In the with block
# Exiting foo
# Tearing Down Wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment