blob: c06ec73f489d06ddb27b2d1cf7ea174e69a3d744 [file] [log] [blame]
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001"""Utilities for with-statement contexts. See PEP 343."""
Brett Cannon9e080e02016-04-08 12:15:27 -07002import abc
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003import sys
Jelle Zijlstra57161aa2017-06-09 08:21:47 -07004import _collections_abc
Nick Coghlan3267a302012-05-21 22:54:43 +10005from collections import deque
Christian Heimes81ee3ef2008-05-04 22:42:01 +00006from functools import wraps
jdemeyer23ab5ee2018-04-13 14:22:46 +02007from types import MethodType
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00008
Jesse-Bakker0784a2e2017-11-23 01:23:28 +01009__all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext",
Jelle Zijlstra176baa32017-12-13 17:19:17 -080010 "AbstractContextManager", "AbstractAsyncContextManager",
Ilya Kulakov1aa094f2018-01-25 12:51:18 -080011 "AsyncExitStack", "ContextDecorator", "ExitStack",
Jelle Zijlstra2e624692017-04-30 18:25:58 -070012 "redirect_stdout", "redirect_stderr", "suppress"]
Brett Cannon9e080e02016-04-08 12:15:27 -070013
14
15class AbstractContextManager(abc.ABC):
16
17 """An abstract base class for context managers."""
18
19 def __enter__(self):
20 """Return `self` upon entering the runtime context."""
21 return self
22
23 @abc.abstractmethod
24 def __exit__(self, exc_type, exc_value, traceback):
25 """Raise any exception triggered within the runtime context."""
26 return None
27
28 @classmethod
29 def __subclasshook__(cls, C):
30 if cls is AbstractContextManager:
Jelle Zijlstra57161aa2017-06-09 08:21:47 -070031 return _collections_abc._check_methods(C, "__enter__", "__exit__")
Brett Cannon9e080e02016-04-08 12:15:27 -070032 return NotImplemented
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000033
Michael Foordb3a89842010-06-30 12:17:50 +000034
Jelle Zijlstra176baa32017-12-13 17:19:17 -080035class AbstractAsyncContextManager(abc.ABC):
36
37 """An abstract base class for asynchronous context managers."""
38
39 async def __aenter__(self):
40 """Return `self` upon entering the runtime context."""
41 return self
42
43 @abc.abstractmethod
44 async def __aexit__(self, exc_type, exc_value, traceback):
45 """Raise any exception triggered within the runtime context."""
46 return None
47
48 @classmethod
49 def __subclasshook__(cls, C):
50 if cls is AbstractAsyncContextManager:
51 return _collections_abc._check_methods(C, "__aenter__",
52 "__aexit__")
53 return NotImplemented
54
55
Michael Foordb3a89842010-06-30 12:17:50 +000056class ContextDecorator(object):
57 "A base class or mixin that enables context managers to work as decorators."
Nick Coghlan0ded3e32011-05-05 23:49:25 +100058
59 def _recreate_cm(self):
60 """Return a recreated instance of self.
Nick Coghlanfdc2c552011-05-06 00:02:12 +100061
Nick Coghlan3267a302012-05-21 22:54:43 +100062 Allows an otherwise one-shot context manager like
Nick Coghlan0ded3e32011-05-05 23:49:25 +100063 _GeneratorContextManager to support use as
Nick Coghlan3267a302012-05-21 22:54:43 +100064 a decorator via implicit recreation.
Nick Coghlanfdc2c552011-05-06 00:02:12 +100065
Nick Coghlan3267a302012-05-21 22:54:43 +100066 This is a private interface just for _GeneratorContextManager.
67 See issue #11647 for details.
Nick Coghlan0ded3e32011-05-05 23:49:25 +100068 """
69 return self
70
Michael Foordb3a89842010-06-30 12:17:50 +000071 def __call__(self, func):
72 @wraps(func)
73 def inner(*args, **kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +100074 with self._recreate_cm():
Michael Foordb3a89842010-06-30 12:17:50 +000075 return func(*args, **kwds)
76 return inner
77
78
Jelle Zijlstra2e624692017-04-30 18:25:58 -070079class _GeneratorContextManagerBase:
80 """Shared functionality for @contextmanager and @asynccontextmanager."""
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000081
Serhiy Storchaka101ff352015-06-28 17:06:07 +030082 def __init__(self, func, args, kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +100083 self.gen = func(*args, **kwds)
84 self.func, self.args, self.kwds = func, args, kwds
Nick Coghlan059def52013-10-26 18:08:15 +100085 # Issue 19330: ensure context manager instances have good docstrings
86 doc = getattr(func, "__doc__", None)
87 if doc is None:
88 doc = type(self).__doc__
89 self.__doc__ = doc
90 # Unfortunately, this still doesn't provide good help output when
91 # inspecting the created context manager instances, since pydoc
92 # currently bypasses the instance docstring and shows the docstring
93 # for the class instead.
94 # See http://bugs.python.org/issue19404 for more details.
Nick Coghlan0ded3e32011-05-05 23:49:25 +100095
Jelle Zijlstra2e624692017-04-30 18:25:58 -070096
97class _GeneratorContextManager(_GeneratorContextManagerBase,
98 AbstractContextManager,
99 ContextDecorator):
100 """Helper for @contextmanager decorator."""
101
Nick Coghlan0ded3e32011-05-05 23:49:25 +1000102 def _recreate_cm(self):
103 # _GCM instances are one-shot context managers, so the
104 # CM must be recreated each time a decorated function is
105 # called
Serhiy Storchaka101ff352015-06-28 17:06:07 +0300106 return self.__class__(self.func, self.args, self.kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000107
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000108 def __enter__(self):
Martin Teichmanndd0e0872018-01-28 05:17:46 +0100109 # do not keep args and kwds alive unnecessarily
110 # they are only needed for recreation, which is not possible anymore
111 del self.args, self.kwds, self.func
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000112 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000113 return next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000114 except StopIteration:
Nick Coghlan8608d262013-10-20 00:30:51 +1000115 raise RuntimeError("generator didn't yield") from None
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000116
117 def __exit__(self, type, value, traceback):
118 if type is None:
119 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000120 next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000121 except StopIteration:
svelankar00c75e92017-04-11 05:11:13 -0400122 return False
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000123 else:
124 raise RuntimeError("generator didn't stop")
125 else:
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000126 if value is None:
127 # Need to force instantiation so we can reliably
128 # tell if we get the same exception back
129 value = type()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000130 try:
131 self.gen.throw(type, value, traceback)
Guido van Rossumb940e112007-01-10 16:19:56 +0000132 except StopIteration as exc:
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400133 # Suppress StopIteration *unless* it's the same exception that
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000134 # was passed to throw(). This prevents a StopIteration
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400135 # raised inside the "with" statement from being suppressed.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000136 return exc is not value
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400137 except RuntimeError as exc:
Nathaniel J. Smithaf88e7e2017-02-12 03:37:24 -0800138 # Don't re-raise the passed in exception. (issue27122)
Gregory P. Smithba2ecd62016-06-14 09:19:20 -0700139 if exc is value:
140 return False
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400141 # Likewise, avoid suppressing if a StopIteration exception
142 # was passed to throw() and later wrapped into a RuntimeError
143 # (see PEP 479).
svelankar00c75e92017-04-11 05:11:13 -0400144 if type is StopIteration and exc.__cause__ is value:
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400145 return False
146 raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000147 except:
148 # only re-raise if it's *not* the exception that was
149 # passed to throw(), because __exit__() must not raise
150 # an exception unless __exit__() itself failed. But throw()
151 # has to raise the exception to signal propagation, so this
152 # fixes the impedance mismatch between the throw() protocol
153 # and the __exit__() protocol.
154 #
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700155 # This cannot use 'except BaseException as exc' (as in the
156 # async implementation) to maintain compatibility with
157 # Python 2, where old-style class exceptions are not caught
158 # by 'except BaseException'.
svelankar00c75e92017-04-11 05:11:13 -0400159 if sys.exc_info()[1] is value:
160 return False
161 raise
162 raise RuntimeError("generator didn't stop after throw()")
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000163
164
Jelle Zijlstra176baa32017-12-13 17:19:17 -0800165class _AsyncGeneratorContextManager(_GeneratorContextManagerBase,
166 AbstractAsyncContextManager):
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700167 """Helper for @asynccontextmanager."""
168
169 async def __aenter__(self):
170 try:
171 return await self.gen.__anext__()
172 except StopAsyncIteration:
173 raise RuntimeError("generator didn't yield") from None
174
175 async def __aexit__(self, typ, value, traceback):
176 if typ is None:
177 try:
178 await self.gen.__anext__()
179 except StopAsyncIteration:
180 return
181 else:
182 raise RuntimeError("generator didn't stop")
183 else:
184 if value is None:
185 value = typ()
186 # See _GeneratorContextManager.__exit__ for comments on subtleties
187 # in this implementation
188 try:
189 await self.gen.athrow(typ, value, traceback)
Yury Selivanov52698c72018-06-07 20:31:26 -0400190 raise RuntimeError("generator didn't stop after athrow()")
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700191 except StopAsyncIteration as exc:
192 return exc is not value
193 except RuntimeError as exc:
194 if exc is value:
195 return False
196 # Avoid suppressing if a StopIteration exception
197 # was passed to throw() and later wrapped into a RuntimeError
198 # (see PEP 479 for sync generators; async generators also
199 # have this behavior). But do this only if the exception wrapped
200 # by the RuntimeError is actully Stop(Async)Iteration (see
201 # issue29692).
202 if isinstance(value, (StopIteration, StopAsyncIteration)):
203 if exc.__cause__ is value:
204 return False
205 raise
206 except BaseException as exc:
207 if exc is not value:
208 raise
209
210
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000211def contextmanager(func):
212 """@contextmanager decorator.
213
214 Typical usage:
215
216 @contextmanager
217 def some_generator(<arguments>):
218 <setup>
219 try:
220 yield <value>
221 finally:
222 <cleanup>
223
224 This makes this:
225
226 with some_generator(<arguments>) as <variable>:
227 <body>
228
229 equivalent to this:
230
231 <setup>
232 try:
233 <variable> = <value>
234 <body>
235 finally:
236 <cleanup>
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000237 """
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000238 @wraps(func)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000239 def helper(*args, **kwds):
Serhiy Storchaka101ff352015-06-28 17:06:07 +0300240 return _GeneratorContextManager(func, args, kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000241 return helper
242
243
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700244def asynccontextmanager(func):
245 """@asynccontextmanager decorator.
246
247 Typical usage:
248
249 @asynccontextmanager
250 async def some_async_generator(<arguments>):
251 <setup>
252 try:
253 yield <value>
254 finally:
255 <cleanup>
256
257 This makes this:
258
259 async with some_async_generator(<arguments>) as <variable>:
260 <body>
261
262 equivalent to this:
263
264 <setup>
265 try:
266 <variable> = <value>
267 <body>
268 finally:
269 <cleanup>
270 """
271 @wraps(func)
272 def helper(*args, **kwds):
273 return _AsyncGeneratorContextManager(func, args, kwds)
274 return helper
275
276
Brett Cannon9e080e02016-04-08 12:15:27 -0700277class closing(AbstractContextManager):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000278 """Context to automatically close something at the end of a block.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000279
280 Code like this:
281
282 with closing(<module>.open(<arguments>)) as f:
283 <block>
284
285 is equivalent to this:
286
287 f = <module>.open(<arguments>)
288 try:
289 <block>
290 finally:
291 f.close()
292
293 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000294 def __init__(self, thing):
295 self.thing = thing
296 def __enter__(self):
297 return self.thing
298 def __exit__(self, *exc_info):
299 self.thing.close()
Nick Coghlan3267a302012-05-21 22:54:43 +1000300
Berker Peksagbb44fe02014-11-28 23:28:06 +0200301
Brett Cannon9e080e02016-04-08 12:15:27 -0700302class _RedirectStream(AbstractContextManager):
Berker Peksagbb44fe02014-11-28 23:28:06 +0200303
304 _stream = None
305
306 def __init__(self, new_target):
307 self._new_target = new_target
308 # We use a list of old targets to make this CM re-entrant
309 self._old_targets = []
310
311 def __enter__(self):
312 self._old_targets.append(getattr(sys, self._stream))
313 setattr(sys, self._stream, self._new_target)
314 return self._new_target
315
316 def __exit__(self, exctype, excinst, exctb):
317 setattr(sys, self._stream, self._old_targets.pop())
318
319
320class redirect_stdout(_RedirectStream):
321 """Context manager for temporarily redirecting stdout to another file.
Nick Coghlan059def52013-10-26 18:08:15 +1000322
323 # How to send help() to stderr
324 with redirect_stdout(sys.stderr):
325 help(dir)
326
327 # How to write help() to a file
328 with open('help.txt', 'w') as f:
329 with redirect_stdout(f):
330 help(pow)
331 """
Nick Coghlan8608d262013-10-20 00:30:51 +1000332
Berker Peksagbb44fe02014-11-28 23:28:06 +0200333 _stream = "stdout"
Nick Coghlan8608d262013-10-20 00:30:51 +1000334
Nick Coghlan8608d262013-10-20 00:30:51 +1000335
Berker Peksagbb44fe02014-11-28 23:28:06 +0200336class redirect_stderr(_RedirectStream):
337 """Context manager for temporarily redirecting stderr to another file."""
338
339 _stream = "stderr"
Raymond Hettinger088cbf22013-10-10 00:46:57 -0700340
Nick Coghlan8608d262013-10-20 00:30:51 +1000341
Brett Cannon9e080e02016-04-08 12:15:27 -0700342class suppress(AbstractContextManager):
Nick Coghlan240f86d2013-10-17 23:40:57 +1000343 """Context manager to suppress specified exceptions
Raymond Hettingere318a882013-03-10 22:26:51 -0700344
Nick Coghlan8608d262013-10-20 00:30:51 +1000345 After the exception is suppressed, execution proceeds with the next
346 statement following the with statement.
Raymond Hettingere318a882013-03-10 22:26:51 -0700347
Nick Coghlan8608d262013-10-20 00:30:51 +1000348 with suppress(FileNotFoundError):
349 os.remove(somefile)
350 # Execution still resumes here if the file was already removed
Raymond Hettingere318a882013-03-10 22:26:51 -0700351 """
Nick Coghlan059def52013-10-26 18:08:15 +1000352
353 def __init__(self, *exceptions):
354 self._exceptions = exceptions
355
356 def __enter__(self):
357 pass
358
359 def __exit__(self, exctype, excinst, exctb):
360 # Unlike isinstance and issubclass, CPython exception handling
361 # currently only looks at the concrete type hierarchy (ignoring
362 # the instance and subclass checking hooks). While Guido considers
363 # that a bug rather than a feature, it's a fairly hard one to fix
364 # due to various internal implementation details. suppress provides
365 # the simpler issubclass based semantics, rather than trying to
366 # exactly reproduce the limitations of the CPython interpreter.
367 #
368 # See http://bugs.python.org/issue12029 for more details
369 return exctype is not None and issubclass(exctype, self._exceptions)
370
Nick Coghlan3267a302012-05-21 22:54:43 +1000371
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800372class _BaseExitStack:
373 """A base class for ExitStack and AsyncExitStack."""
Nick Coghlan3267a302012-05-21 22:54:43 +1000374
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800375 @staticmethod
376 def _create_exit_wrapper(cm, cm_exit):
jdemeyer23ab5ee2018-04-13 14:22:46 +0200377 return MethodType(cm_exit, cm)
Nick Coghlan3267a302012-05-21 22:54:43 +1000378
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800379 @staticmethod
380 def _create_cb_wrapper(callback, *args, **kwds):
381 def _exit_wrapper(exc_type, exc, tb):
382 callback(*args, **kwds)
383 return _exit_wrapper
Nick Coghlan3267a302012-05-21 22:54:43 +1000384
Nick Coghlan3267a302012-05-21 22:54:43 +1000385 def __init__(self):
386 self._exit_callbacks = deque()
387
388 def pop_all(self):
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800389 """Preserve the context stack by transferring it to a new instance."""
Nick Coghlan3267a302012-05-21 22:54:43 +1000390 new_stack = type(self)()
391 new_stack._exit_callbacks = self._exit_callbacks
392 self._exit_callbacks = deque()
393 return new_stack
394
Nick Coghlan3267a302012-05-21 22:54:43 +1000395 def push(self, exit):
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800396 """Registers a callback with the standard __exit__ method signature.
Nick Coghlan3267a302012-05-21 22:54:43 +1000397
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800398 Can suppress exceptions the same way __exit__ method can.
Nick Coghlan3267a302012-05-21 22:54:43 +1000399 Also accepts any object with an __exit__ method (registering a call
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800400 to the method instead of the object itself).
Nick Coghlan3267a302012-05-21 22:54:43 +1000401 """
402 # We use an unbound method rather than a bound method to follow
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800403 # the standard lookup behaviour for special methods.
Nick Coghlan3267a302012-05-21 22:54:43 +1000404 _cb_type = type(exit)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800405
Nick Coghlan3267a302012-05-21 22:54:43 +1000406 try:
407 exit_method = _cb_type.__exit__
408 except AttributeError:
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800409 # Not a context manager, so assume it's a callable.
410 self._push_exit_callback(exit)
Nick Coghlan3267a302012-05-21 22:54:43 +1000411 else:
412 self._push_cm_exit(exit, exit_method)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800413 return exit # Allow use as a decorator.
Nick Coghlan3267a302012-05-21 22:54:43 +1000414
415 def enter_context(self, cm):
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800416 """Enters the supplied context manager.
Nick Coghlan3267a302012-05-21 22:54:43 +1000417
418 If successful, also pushes its __exit__ method as a callback and
419 returns the result of the __enter__ method.
420 """
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800421 # We look up the special methods on the type to match the with
422 # statement.
Nick Coghlan3267a302012-05-21 22:54:43 +1000423 _cm_type = type(cm)
424 _exit = _cm_type.__exit__
425 result = _cm_type.__enter__(cm)
426 self._push_cm_exit(cm, _exit)
427 return result
428
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800429 def callback(self, callback, *args, **kwds):
430 """Registers an arbitrary callback and arguments.
431
432 Cannot suppress exceptions.
433 """
434 _exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds)
435
436 # We changed the signature, so using @wraps is not appropriate, but
437 # setting __wrapped__ may still help with introspection.
438 _exit_wrapper.__wrapped__ = callback
439 self._push_exit_callback(_exit_wrapper)
440 return callback # Allow use as a decorator
441
442 def _push_cm_exit(self, cm, cm_exit):
443 """Helper to correctly register callbacks to __exit__ methods."""
444 _exit_wrapper = self._create_exit_wrapper(cm, cm_exit)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800445 self._push_exit_callback(_exit_wrapper, True)
446
447 def _push_exit_callback(self, callback, is_sync=True):
448 self._exit_callbacks.append((is_sync, callback))
449
450
451# Inspired by discussions on http://bugs.python.org/issue13585
452class ExitStack(_BaseExitStack, AbstractContextManager):
453 """Context manager for dynamic management of a stack of exit callbacks.
454
455 For example:
456 with ExitStack() as stack:
457 files = [stack.enter_context(open(fname)) for fname in filenames]
458 # All opened files will automatically be closed at the end of
459 # the with statement, even if attempts to open files later
460 # in the list raise an exception.
461 """
462
463 def __enter__(self):
464 return self
Nick Coghlan3267a302012-05-21 22:54:43 +1000465
Nick Coghlan3267a302012-05-21 22:54:43 +1000466 def __exit__(self, *exc_details):
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000467 received_exc = exc_details[0] is not None
468
Nick Coghlan77452fc2012-06-01 22:48:32 +1000469 # We manipulate the exception state so it behaves as though
470 # we were actually nesting multiple with statements
471 frame_exc = sys.exc_info()[1]
472 def _fix_exception_context(new_exc, old_exc):
Nick Coghlanadd94c92014-01-24 23:05:45 +1000473 # Context may not be correct, so find the end of the chain
Nick Coghlan77452fc2012-06-01 22:48:32 +1000474 while 1:
475 exc_context = new_exc.__context__
Nick Coghlan09761e72014-01-22 22:24:46 +1000476 if exc_context is old_exc:
477 # Context is already set correctly (see issue 20317)
478 return
479 if exc_context is None or exc_context is frame_exc:
Nick Coghlan77452fc2012-06-01 22:48:32 +1000480 break
481 new_exc = exc_context
Nick Coghlan09761e72014-01-22 22:24:46 +1000482 # Change the end of the chain to point to the exception
483 # we expect it to reference
Nick Coghlan77452fc2012-06-01 22:48:32 +1000484 new_exc.__context__ = old_exc
485
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000486 # Callbacks are invoked in LIFO order to match the behaviour of
487 # nested context managers
488 suppressed_exc = False
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000489 pending_raise = False
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000490 while self._exit_callbacks:
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800491 is_sync, cb = self._exit_callbacks.pop()
492 assert is_sync
Nick Coghlan3267a302012-05-21 22:54:43 +1000493 try:
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000494 if cb(*exc_details):
495 suppressed_exc = True
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000496 pending_raise = False
Nick Coghlan3267a302012-05-21 22:54:43 +1000497 exc_details = (None, None, None)
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000498 except:
499 new_exc_details = sys.exc_info()
Nick Coghlan77452fc2012-06-01 22:48:32 +1000500 # simulate the stack of exceptions by setting the context
501 _fix_exception_context(new_exc_details[1], exc_details[1])
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000502 pending_raise = True
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000503 exc_details = new_exc_details
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000504 if pending_raise:
505 try:
506 # bare "raise exc_details[1]" replaces our carefully
507 # set-up context
508 fixed_ctx = exc_details[1].__context__
509 raise exc_details[1]
510 except BaseException:
511 exc_details[1].__context__ = fixed_ctx
512 raise
513 return received_exc and suppressed_exc
Jesse-Bakker0784a2e2017-11-23 01:23:28 +0100514
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800515 def close(self):
516 """Immediately unwind the context stack."""
517 self.__exit__(None, None, None)
518
519
520# Inspired by discussions on https://bugs.python.org/issue29302
521class AsyncExitStack(_BaseExitStack, AbstractAsyncContextManager):
522 """Async context manager for dynamic management of a stack of exit
523 callbacks.
524
525 For example:
526 async with AsyncExitStack() as stack:
527 connections = [await stack.enter_async_context(get_connection())
528 for i in range(5)]
529 # All opened connections will automatically be released at the
530 # end of the async with statement, even if attempts to open a
531 # connection later in the list raise an exception.
532 """
533
534 @staticmethod
535 def _create_async_exit_wrapper(cm, cm_exit):
jdemeyer23ab5ee2018-04-13 14:22:46 +0200536 return MethodType(cm_exit, cm)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800537
538 @staticmethod
539 def _create_async_cb_wrapper(callback, *args, **kwds):
540 async def _exit_wrapper(exc_type, exc, tb):
541 await callback(*args, **kwds)
542 return _exit_wrapper
543
544 async def enter_async_context(self, cm):
545 """Enters the supplied async context manager.
546
547 If successful, also pushes its __aexit__ method as a callback and
548 returns the result of the __aenter__ method.
549 """
550 _cm_type = type(cm)
551 _exit = _cm_type.__aexit__
552 result = await _cm_type.__aenter__(cm)
553 self._push_async_cm_exit(cm, _exit)
554 return result
555
556 def push_async_exit(self, exit):
557 """Registers a coroutine function with the standard __aexit__ method
558 signature.
559
560 Can suppress exceptions the same way __aexit__ method can.
561 Also accepts any object with an __aexit__ method (registering a call
562 to the method instead of the object itself).
563 """
564 _cb_type = type(exit)
565 try:
566 exit_method = _cb_type.__aexit__
567 except AttributeError:
568 # Not an async context manager, so assume it's a coroutine function
569 self._push_exit_callback(exit, False)
570 else:
571 self._push_async_cm_exit(exit, exit_method)
572 return exit # Allow use as a decorator
573
574 def push_async_callback(self, callback, *args, **kwds):
575 """Registers an arbitrary coroutine function and arguments.
576
577 Cannot suppress exceptions.
578 """
579 _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds)
580
581 # We changed the signature, so using @wraps is not appropriate, but
582 # setting __wrapped__ may still help with introspection.
583 _exit_wrapper.__wrapped__ = callback
584 self._push_exit_callback(_exit_wrapper, False)
585 return callback # Allow use as a decorator
586
587 async def aclose(self):
588 """Immediately unwind the context stack."""
589 await self.__aexit__(None, None, None)
590
591 def _push_async_cm_exit(self, cm, cm_exit):
592 """Helper to correctly register coroutine function to __aexit__
593 method."""
594 _exit_wrapper = self._create_async_exit_wrapper(cm, cm_exit)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800595 self._push_exit_callback(_exit_wrapper, False)
596
597 async def __aenter__(self):
598 return self
599
600 async def __aexit__(self, *exc_details):
601 received_exc = exc_details[0] is not None
602
603 # We manipulate the exception state so it behaves as though
604 # we were actually nesting multiple with statements
605 frame_exc = sys.exc_info()[1]
606 def _fix_exception_context(new_exc, old_exc):
607 # Context may not be correct, so find the end of the chain
608 while 1:
609 exc_context = new_exc.__context__
610 if exc_context is old_exc:
611 # Context is already set correctly (see issue 20317)
612 return
613 if exc_context is None or exc_context is frame_exc:
614 break
615 new_exc = exc_context
616 # Change the end of the chain to point to the exception
617 # we expect it to reference
618 new_exc.__context__ = old_exc
619
620 # Callbacks are invoked in LIFO order to match the behaviour of
621 # nested context managers
622 suppressed_exc = False
623 pending_raise = False
624 while self._exit_callbacks:
625 is_sync, cb = self._exit_callbacks.pop()
626 try:
627 if is_sync:
628 cb_suppress = cb(*exc_details)
629 else:
630 cb_suppress = await cb(*exc_details)
631
632 if cb_suppress:
633 suppressed_exc = True
634 pending_raise = False
635 exc_details = (None, None, None)
636 except:
637 new_exc_details = sys.exc_info()
638 # simulate the stack of exceptions by setting the context
639 _fix_exception_context(new_exc_details[1], exc_details[1])
640 pending_raise = True
641 exc_details = new_exc_details
642 if pending_raise:
643 try:
644 # bare "raise exc_details[1]" replaces our carefully
645 # set-up context
646 fixed_ctx = exc_details[1].__context__
647 raise exc_details[1]
648 except BaseException:
649 exc_details[1].__context__ = fixed_ctx
650 raise
651 return received_exc and suppressed_exc
652
Jesse-Bakker0784a2e2017-11-23 01:23:28 +0100653
654class nullcontext(AbstractContextManager):
655 """Context manager that does no additional processing.
656
657 Used as a stand-in for a normal context manager, when a particular
658 block of code is only sometimes used with a normal context manager:
659
660 cm = optional_cm if condition else nullcontext()
661 with cm:
662 # Perform operation, using optional_cm if condition is True
663 """
664
665 def __init__(self, enter_result=None):
666 self.enter_result = enter_result
667
668 def __enter__(self):
669 return self.enter_result
670
671 def __exit__(self, *excinfo):
672 pass