Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 1 | """Utilities for with-statement contexts. See PEP 343.""" |
Brett Cannon | 9e080e0 | 2016-04-08 12:15:27 -0700 | [diff] [blame] | 2 | import abc |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 3 | import sys |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 4 | from collections import deque |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 5 | from functools import wraps |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 6 | |
Brett Cannon | 9e080e0 | 2016-04-08 12:15:27 -0700 | [diff] [blame] | 7 | __all__ = ["contextmanager", "closing", "AbstractContextManager", |
| 8 | "ContextDecorator", "ExitStack", "redirect_stdout", |
| 9 | "redirect_stderr", "suppress"] |
| 10 | |
| 11 | |
| 12 | class AbstractContextManager(abc.ABC): |
| 13 | |
| 14 | """An abstract base class for context managers.""" |
| 15 | |
| 16 | def __enter__(self): |
| 17 | """Return `self` upon entering the runtime context.""" |
| 18 | return self |
| 19 | |
| 20 | @abc.abstractmethod |
| 21 | def __exit__(self, exc_type, exc_value, traceback): |
| 22 | """Raise any exception triggered within the runtime context.""" |
| 23 | return None |
| 24 | |
| 25 | @classmethod |
| 26 | def __subclasshook__(cls, C): |
| 27 | if cls is AbstractContextManager: |
| 28 | if (any("__enter__" in B.__dict__ for B in C.__mro__) and |
| 29 | any("__exit__" in B.__dict__ for B in C.__mro__)): |
Brett Cannon | 8bd092b | 2016-04-08 12:16:16 -0700 | [diff] [blame] | 30 | return True |
Brett Cannon | 9e080e0 | 2016-04-08 12:15:27 -0700 | [diff] [blame] | 31 | return NotImplemented |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 32 | |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 33 | |
| 34 | class ContextDecorator(object): |
| 35 | "A base class or mixin that enables context managers to work as decorators." |
Nick Coghlan | 0ded3e3 | 2011-05-05 23:49:25 +1000 | [diff] [blame] | 36 | |
| 37 | def _recreate_cm(self): |
| 38 | """Return a recreated instance of self. |
Nick Coghlan | fdc2c55 | 2011-05-06 00:02:12 +1000 | [diff] [blame] | 39 | |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 40 | Allows an otherwise one-shot context manager like |
Nick Coghlan | 0ded3e3 | 2011-05-05 23:49:25 +1000 | [diff] [blame] | 41 | _GeneratorContextManager to support use as |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 42 | a decorator via implicit recreation. |
Nick Coghlan | fdc2c55 | 2011-05-06 00:02:12 +1000 | [diff] [blame] | 43 | |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 44 | This is a private interface just for _GeneratorContextManager. |
| 45 | See issue #11647 for details. |
Nick Coghlan | 0ded3e3 | 2011-05-05 23:49:25 +1000 | [diff] [blame] | 46 | """ |
| 47 | return self |
| 48 | |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 49 | def __call__(self, func): |
| 50 | @wraps(func) |
| 51 | def inner(*args, **kwds): |
Nick Coghlan | 0ded3e3 | 2011-05-05 23:49:25 +1000 | [diff] [blame] | 52 | with self._recreate_cm(): |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 53 | return func(*args, **kwds) |
| 54 | return inner |
| 55 | |
| 56 | |
Brett Cannon | 9e080e0 | 2016-04-08 12:15:27 -0700 | [diff] [blame] | 57 | class _GeneratorContextManager(ContextDecorator, AbstractContextManager): |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 58 | """Helper for @contextmanager decorator.""" |
| 59 | |
Serhiy Storchaka | 101ff35 | 2015-06-28 17:06:07 +0300 | [diff] [blame] | 60 | def __init__(self, func, args, kwds): |
Nick Coghlan | 0ded3e3 | 2011-05-05 23:49:25 +1000 | [diff] [blame] | 61 | self.gen = func(*args, **kwds) |
| 62 | self.func, self.args, self.kwds = func, args, kwds |
Nick Coghlan | 059def5 | 2013-10-26 18:08:15 +1000 | [diff] [blame] | 63 | # Issue 19330: ensure context manager instances have good docstrings |
| 64 | doc = getattr(func, "__doc__", None) |
| 65 | if doc is None: |
| 66 | doc = type(self).__doc__ |
| 67 | self.__doc__ = doc |
| 68 | # Unfortunately, this still doesn't provide good help output when |
| 69 | # inspecting the created context manager instances, since pydoc |
| 70 | # currently bypasses the instance docstring and shows the docstring |
| 71 | # for the class instead. |
| 72 | # See http://bugs.python.org/issue19404 for more details. |
Nick Coghlan | 0ded3e3 | 2011-05-05 23:49:25 +1000 | [diff] [blame] | 73 | |
| 74 | def _recreate_cm(self): |
| 75 | # _GCM instances are one-shot context managers, so the |
| 76 | # CM must be recreated each time a decorated function is |
| 77 | # called |
Serhiy Storchaka | 101ff35 | 2015-06-28 17:06:07 +0300 | [diff] [blame] | 78 | return self.__class__(self.func, self.args, self.kwds) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 79 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 80 | def __enter__(self): |
| 81 | try: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 82 | return next(self.gen) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 83 | except StopIteration: |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 84 | raise RuntimeError("generator didn't yield") from None |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 85 | |
| 86 | def __exit__(self, type, value, traceback): |
| 87 | if type is None: |
| 88 | try: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 89 | next(self.gen) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 90 | except StopIteration: |
svelankar | 00c75e9 | 2017-04-11 05:11:13 -0400 | [diff] [blame^] | 91 | return False |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 92 | else: |
| 93 | raise RuntimeError("generator didn't stop") |
| 94 | else: |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 95 | if value is None: |
| 96 | # Need to force instantiation so we can reliably |
| 97 | # tell if we get the same exception back |
| 98 | value = type() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 99 | try: |
| 100 | self.gen.throw(type, value, traceback) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 101 | except StopIteration as exc: |
Yury Selivanov | 8170e8c | 2015-05-09 11:44:30 -0400 | [diff] [blame] | 102 | # Suppress StopIteration *unless* it's the same exception that |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 103 | # was passed to throw(). This prevents a StopIteration |
Yury Selivanov | 8170e8c | 2015-05-09 11:44:30 -0400 | [diff] [blame] | 104 | # raised inside the "with" statement from being suppressed. |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 105 | return exc is not value |
Yury Selivanov | 8170e8c | 2015-05-09 11:44:30 -0400 | [diff] [blame] | 106 | except RuntimeError as exc: |
Nathaniel J. Smith | af88e7e | 2017-02-12 03:37:24 -0800 | [diff] [blame] | 107 | # Don't re-raise the passed in exception. (issue27122) |
Gregory P. Smith | ba2ecd6 | 2016-06-14 09:19:20 -0700 | [diff] [blame] | 108 | if exc is value: |
| 109 | return False |
Yury Selivanov | 8170e8c | 2015-05-09 11:44:30 -0400 | [diff] [blame] | 110 | # Likewise, avoid suppressing if a StopIteration exception |
| 111 | # was passed to throw() and later wrapped into a RuntimeError |
| 112 | # (see PEP 479). |
svelankar | 00c75e9 | 2017-04-11 05:11:13 -0400 | [diff] [blame^] | 113 | if type is StopIteration and exc.__cause__ is value: |
Yury Selivanov | 8170e8c | 2015-05-09 11:44:30 -0400 | [diff] [blame] | 114 | return False |
| 115 | raise |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 116 | except: |
| 117 | # only re-raise if it's *not* the exception that was |
| 118 | # passed to throw(), because __exit__() must not raise |
| 119 | # an exception unless __exit__() itself failed. But throw() |
| 120 | # has to raise the exception to signal propagation, so this |
| 121 | # fixes the impedance mismatch between the throw() protocol |
| 122 | # and the __exit__() protocol. |
| 123 | # |
svelankar | 00c75e9 | 2017-04-11 05:11:13 -0400 | [diff] [blame^] | 124 | if sys.exc_info()[1] is value: |
| 125 | return False |
| 126 | raise |
| 127 | raise RuntimeError("generator didn't stop after throw()") |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 128 | |
| 129 | |
| 130 | def contextmanager(func): |
| 131 | """@contextmanager decorator. |
| 132 | |
| 133 | Typical usage: |
| 134 | |
| 135 | @contextmanager |
| 136 | def some_generator(<arguments>): |
| 137 | <setup> |
| 138 | try: |
| 139 | yield <value> |
| 140 | finally: |
| 141 | <cleanup> |
| 142 | |
| 143 | This makes this: |
| 144 | |
| 145 | with some_generator(<arguments>) as <variable>: |
| 146 | <body> |
| 147 | |
| 148 | equivalent to this: |
| 149 | |
| 150 | <setup> |
| 151 | try: |
| 152 | <variable> = <value> |
| 153 | <body> |
| 154 | finally: |
| 155 | <cleanup> |
| 156 | |
| 157 | """ |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 158 | @wraps(func) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 159 | def helper(*args, **kwds): |
Serhiy Storchaka | 101ff35 | 2015-06-28 17:06:07 +0300 | [diff] [blame] | 160 | return _GeneratorContextManager(func, args, kwds) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 161 | return helper |
| 162 | |
| 163 | |
Brett Cannon | 9e080e0 | 2016-04-08 12:15:27 -0700 | [diff] [blame] | 164 | class closing(AbstractContextManager): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 165 | """Context to automatically close something at the end of a block. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 166 | |
| 167 | Code like this: |
| 168 | |
| 169 | with closing(<module>.open(<arguments>)) as f: |
| 170 | <block> |
| 171 | |
| 172 | is equivalent to this: |
| 173 | |
| 174 | f = <module>.open(<arguments>) |
| 175 | try: |
| 176 | <block> |
| 177 | finally: |
| 178 | f.close() |
| 179 | |
| 180 | """ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 181 | def __init__(self, thing): |
| 182 | self.thing = thing |
| 183 | def __enter__(self): |
| 184 | return self.thing |
| 185 | def __exit__(self, *exc_info): |
| 186 | self.thing.close() |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 187 | |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 188 | |
Brett Cannon | 9e080e0 | 2016-04-08 12:15:27 -0700 | [diff] [blame] | 189 | class _RedirectStream(AbstractContextManager): |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 190 | |
| 191 | _stream = None |
| 192 | |
| 193 | def __init__(self, new_target): |
| 194 | self._new_target = new_target |
| 195 | # We use a list of old targets to make this CM re-entrant |
| 196 | self._old_targets = [] |
| 197 | |
| 198 | def __enter__(self): |
| 199 | self._old_targets.append(getattr(sys, self._stream)) |
| 200 | setattr(sys, self._stream, self._new_target) |
| 201 | return self._new_target |
| 202 | |
| 203 | def __exit__(self, exctype, excinst, exctb): |
| 204 | setattr(sys, self._stream, self._old_targets.pop()) |
| 205 | |
| 206 | |
| 207 | class redirect_stdout(_RedirectStream): |
| 208 | """Context manager for temporarily redirecting stdout to another file. |
Nick Coghlan | 059def5 | 2013-10-26 18:08:15 +1000 | [diff] [blame] | 209 | |
| 210 | # How to send help() to stderr |
| 211 | with redirect_stdout(sys.stderr): |
| 212 | help(dir) |
| 213 | |
| 214 | # How to write help() to a file |
| 215 | with open('help.txt', 'w') as f: |
| 216 | with redirect_stdout(f): |
| 217 | help(pow) |
| 218 | """ |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 219 | |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 220 | _stream = "stdout" |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 221 | |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 222 | |
Berker Peksag | bb44fe0 | 2014-11-28 23:28:06 +0200 | [diff] [blame] | 223 | class redirect_stderr(_RedirectStream): |
| 224 | """Context manager for temporarily redirecting stderr to another file.""" |
| 225 | |
| 226 | _stream = "stderr" |
Raymond Hettinger | 088cbf2 | 2013-10-10 00:46:57 -0700 | [diff] [blame] | 227 | |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 228 | |
Brett Cannon | 9e080e0 | 2016-04-08 12:15:27 -0700 | [diff] [blame] | 229 | class suppress(AbstractContextManager): |
Nick Coghlan | 240f86d | 2013-10-17 23:40:57 +1000 | [diff] [blame] | 230 | """Context manager to suppress specified exceptions |
Raymond Hettinger | e318a88 | 2013-03-10 22:26:51 -0700 | [diff] [blame] | 231 | |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 232 | After the exception is suppressed, execution proceeds with the next |
| 233 | statement following the with statement. |
Raymond Hettinger | e318a88 | 2013-03-10 22:26:51 -0700 | [diff] [blame] | 234 | |
Nick Coghlan | 8608d26 | 2013-10-20 00:30:51 +1000 | [diff] [blame] | 235 | with suppress(FileNotFoundError): |
| 236 | os.remove(somefile) |
| 237 | # Execution still resumes here if the file was already removed |
Raymond Hettinger | e318a88 | 2013-03-10 22:26:51 -0700 | [diff] [blame] | 238 | """ |
Nick Coghlan | 059def5 | 2013-10-26 18:08:15 +1000 | [diff] [blame] | 239 | |
| 240 | def __init__(self, *exceptions): |
| 241 | self._exceptions = exceptions |
| 242 | |
| 243 | def __enter__(self): |
| 244 | pass |
| 245 | |
| 246 | def __exit__(self, exctype, excinst, exctb): |
| 247 | # Unlike isinstance and issubclass, CPython exception handling |
| 248 | # currently only looks at the concrete type hierarchy (ignoring |
| 249 | # the instance and subclass checking hooks). While Guido considers |
| 250 | # that a bug rather than a feature, it's a fairly hard one to fix |
| 251 | # due to various internal implementation details. suppress provides |
| 252 | # the simpler issubclass based semantics, rather than trying to |
| 253 | # exactly reproduce the limitations of the CPython interpreter. |
| 254 | # |
| 255 | # See http://bugs.python.org/issue12029 for more details |
| 256 | return exctype is not None and issubclass(exctype, self._exceptions) |
| 257 | |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 258 | |
| 259 | # Inspired by discussions on http://bugs.python.org/issue13585 |
Brett Cannon | 9e080e0 | 2016-04-08 12:15:27 -0700 | [diff] [blame] | 260 | class ExitStack(AbstractContextManager): |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 261 | """Context manager for dynamic management of a stack of exit callbacks |
| 262 | |
| 263 | For example: |
| 264 | |
| 265 | with ExitStack() as stack: |
| 266 | files = [stack.enter_context(open(fname)) for fname in filenames] |
| 267 | # All opened files will automatically be closed at the end of |
| 268 | # the with statement, even if attempts to open files later |
Andrew Svetlov | 5b89840 | 2012-12-18 21:26:36 +0200 | [diff] [blame] | 269 | # in the list raise an exception |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 270 | |
| 271 | """ |
| 272 | def __init__(self): |
| 273 | self._exit_callbacks = deque() |
| 274 | |
| 275 | def pop_all(self): |
| 276 | """Preserve the context stack by transferring it to a new instance""" |
| 277 | new_stack = type(self)() |
| 278 | new_stack._exit_callbacks = self._exit_callbacks |
| 279 | self._exit_callbacks = deque() |
| 280 | return new_stack |
| 281 | |
| 282 | def _push_cm_exit(self, cm, cm_exit): |
| 283 | """Helper to correctly register callbacks to __exit__ methods""" |
| 284 | def _exit_wrapper(*exc_details): |
| 285 | return cm_exit(cm, *exc_details) |
| 286 | _exit_wrapper.__self__ = cm |
| 287 | self.push(_exit_wrapper) |
| 288 | |
| 289 | def push(self, exit): |
| 290 | """Registers a callback with the standard __exit__ method signature |
| 291 | |
| 292 | Can suppress exceptions the same way __exit__ methods can. |
| 293 | |
| 294 | Also accepts any object with an __exit__ method (registering a call |
| 295 | to the method instead of the object itself) |
| 296 | """ |
| 297 | # We use an unbound method rather than a bound method to follow |
| 298 | # the standard lookup behaviour for special methods |
| 299 | _cb_type = type(exit) |
| 300 | try: |
| 301 | exit_method = _cb_type.__exit__ |
| 302 | except AttributeError: |
| 303 | # Not a context manager, so assume its a callable |
| 304 | self._exit_callbacks.append(exit) |
| 305 | else: |
| 306 | self._push_cm_exit(exit, exit_method) |
| 307 | return exit # Allow use as a decorator |
| 308 | |
| 309 | def callback(self, callback, *args, **kwds): |
| 310 | """Registers an arbitrary callback and arguments. |
| 311 | |
| 312 | Cannot suppress exceptions. |
| 313 | """ |
| 314 | def _exit_wrapper(exc_type, exc, tb): |
| 315 | callback(*args, **kwds) |
| 316 | # We changed the signature, so using @wraps is not appropriate, but |
| 317 | # setting __wrapped__ may still help with introspection |
| 318 | _exit_wrapper.__wrapped__ = callback |
| 319 | self.push(_exit_wrapper) |
| 320 | return callback # Allow use as a decorator |
| 321 | |
| 322 | def enter_context(self, cm): |
| 323 | """Enters the supplied context manager |
| 324 | |
| 325 | If successful, also pushes its __exit__ method as a callback and |
| 326 | returns the result of the __enter__ method. |
| 327 | """ |
| 328 | # We look up the special methods on the type to match the with statement |
| 329 | _cm_type = type(cm) |
| 330 | _exit = _cm_type.__exit__ |
| 331 | result = _cm_type.__enter__(cm) |
| 332 | self._push_cm_exit(cm, _exit) |
| 333 | return result |
| 334 | |
| 335 | def close(self): |
| 336 | """Immediately unwind the context stack""" |
| 337 | self.__exit__(None, None, None) |
| 338 | |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 339 | def __exit__(self, *exc_details): |
Nick Coghlan | 1a33b2f | 2013-10-01 23:24:56 +1000 | [diff] [blame] | 340 | received_exc = exc_details[0] is not None |
| 341 | |
Nick Coghlan | 77452fc | 2012-06-01 22:48:32 +1000 | [diff] [blame] | 342 | # We manipulate the exception state so it behaves as though |
| 343 | # we were actually nesting multiple with statements |
| 344 | frame_exc = sys.exc_info()[1] |
| 345 | def _fix_exception_context(new_exc, old_exc): |
Nick Coghlan | add94c9 | 2014-01-24 23:05:45 +1000 | [diff] [blame] | 346 | # Context may not be correct, so find the end of the chain |
Nick Coghlan | 77452fc | 2012-06-01 22:48:32 +1000 | [diff] [blame] | 347 | while 1: |
| 348 | exc_context = new_exc.__context__ |
Nick Coghlan | 09761e7 | 2014-01-22 22:24:46 +1000 | [diff] [blame] | 349 | if exc_context is old_exc: |
| 350 | # Context is already set correctly (see issue 20317) |
| 351 | return |
| 352 | if exc_context is None or exc_context is frame_exc: |
Nick Coghlan | 77452fc | 2012-06-01 22:48:32 +1000 | [diff] [blame] | 353 | break |
| 354 | new_exc = exc_context |
Nick Coghlan | 09761e7 | 2014-01-22 22:24:46 +1000 | [diff] [blame] | 355 | # Change the end of the chain to point to the exception |
| 356 | # we expect it to reference |
Nick Coghlan | 77452fc | 2012-06-01 22:48:32 +1000 | [diff] [blame] | 357 | new_exc.__context__ = old_exc |
| 358 | |
Nick Coghlan | a5bd2a1 | 2012-06-01 00:00:38 +1000 | [diff] [blame] | 359 | # Callbacks are invoked in LIFO order to match the behaviour of |
| 360 | # nested context managers |
| 361 | suppressed_exc = False |
Nick Coghlan | 1a33b2f | 2013-10-01 23:24:56 +1000 | [diff] [blame] | 362 | pending_raise = False |
Nick Coghlan | a5bd2a1 | 2012-06-01 00:00:38 +1000 | [diff] [blame] | 363 | while self._exit_callbacks: |
| 364 | cb = self._exit_callbacks.pop() |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 365 | try: |
Nick Coghlan | a5bd2a1 | 2012-06-01 00:00:38 +1000 | [diff] [blame] | 366 | if cb(*exc_details): |
| 367 | suppressed_exc = True |
Nick Coghlan | 1a33b2f | 2013-10-01 23:24:56 +1000 | [diff] [blame] | 368 | pending_raise = False |
Nick Coghlan | 3267a30 | 2012-05-21 22:54:43 +1000 | [diff] [blame] | 369 | exc_details = (None, None, None) |
Nick Coghlan | a5bd2a1 | 2012-06-01 00:00:38 +1000 | [diff] [blame] | 370 | except: |
| 371 | new_exc_details = sys.exc_info() |
Nick Coghlan | 77452fc | 2012-06-01 22:48:32 +1000 | [diff] [blame] | 372 | # simulate the stack of exceptions by setting the context |
| 373 | _fix_exception_context(new_exc_details[1], exc_details[1]) |
Nick Coghlan | 1a33b2f | 2013-10-01 23:24:56 +1000 | [diff] [blame] | 374 | pending_raise = True |
Nick Coghlan | a5bd2a1 | 2012-06-01 00:00:38 +1000 | [diff] [blame] | 375 | exc_details = new_exc_details |
Nick Coghlan | 1a33b2f | 2013-10-01 23:24:56 +1000 | [diff] [blame] | 376 | if pending_raise: |
| 377 | try: |
| 378 | # bare "raise exc_details[1]" replaces our carefully |
| 379 | # set-up context |
| 380 | fixed_ctx = exc_details[1].__context__ |
| 381 | raise exc_details[1] |
| 382 | except BaseException: |
| 383 | exc_details[1].__context__ = fixed_ctx |
| 384 | raise |
| 385 | return received_exc and suppressed_exc |