Skip to content

Commit

Permalink
contextlib: modify ExitStack to work in uPy
Browse files Browse the repository at this point in the history
  • Loading branch information
dxxb committed Oct 20, 2015
1 parent 4977b21 commit f16304f
Showing 1 changed file with 0 additions and 11 deletions.
11 changes: 0 additions & 11 deletions contextlib/contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,15 +165,12 @@ def __exit__(self, exctype, excinst, exctb):
# Inspired by discussions on http://bugs.python.org/issue13585
class ExitStack(object):
"""Context manager for dynamic management of a stack of exit callbacks
For example:
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
"""
def __init__(self):
self._exit_callbacks = deque()
Expand All @@ -189,14 +186,11 @@ def _push_cm_exit(self, cm, cm_exit):
"""Helper to correctly register callbacks to __exit__ methods"""
def _exit_wrapper(*exc_details):
return cm_exit(cm, *exc_details)
_exit_wrapper.__self__ = cm
self.push(_exit_wrapper)

def push(self, exit):
"""Registers a callback with the standard __exit__ method signature
Can suppress exceptions the same way __exit__ methods can.
Also accepts any object with an __exit__ method (registering a call
to the method instead of the object itself)
"""
Expand All @@ -214,20 +208,15 @@ def push(self, exit):

def callback(self, callback, *args, **kwds):
"""Registers an arbitrary callback and arguments.
Cannot suppress exceptions.
"""
def _exit_wrapper(exc_type, exc, tb):
callback(*args, **kwds)
# We changed the signature, so using @wraps is not appropriate, but
# setting __wrapped__ may still help with introspection
_exit_wrapper.__wrapped__ = callback
self.push(_exit_wrapper)
return callback # Allow use as a decorator

def enter_context(self, cm):
"""Enters the supplied context manager
If successful, also pushes its __exit__ method as a callback and
returns the result of the __enter__ method.
"""
Expand Down

0 comments on commit f16304f

Please sign in to comment.