blob: ef8f8c9f55bcd3f688bf8f29ca773e05930b7c35 [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
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00007
Jesse-Bakker0784a2e2017-11-23 01:23:28 +01008__all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext",
Jelle Zijlstra176baa32017-12-13 17:19:17 -08009 "AbstractContextManager", "AbstractAsyncContextManager",
Ilya Kulakov1aa094f2018-01-25 12:51:18 -080010 "AsyncExitStack", "ContextDecorator", "ExitStack",
Jelle Zijlstra2e624692017-04-30 18:25:58 -070011 "redirect_stdout", "redirect_stderr", "suppress"]
Brett Cannon9e080e02016-04-08 12:15:27 -070012
13
14class AbstractContextManager(abc.ABC):
15
16 """An abstract base class for context managers."""
17
18 def __enter__(self):
19 """Return `self` upon entering the runtime context."""
20 return self
21
22 @abc.abstractmethod
23 def __exit__(self, exc_type, exc_value, traceback):
24 """Raise any exception triggered within the runtime context."""
25 return None
26
27 @classmethod
28 def __subclasshook__(cls, C):
29 if cls is AbstractContextManager:
Jelle Zijlstra57161aa2017-06-09 08:21:47 -070030 return _collections_abc._check_methods(C, "__enter__", "__exit__")
Brett Cannon9e080e02016-04-08 12:15:27 -070031 return NotImplemented
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000032
Michael Foordb3a89842010-06-30 12:17:50 +000033
Jelle Zijlstra176baa32017-12-13 17:19:17 -080034class AbstractAsyncContextManager(abc.ABC):
35
36 """An abstract base class for asynchronous context managers."""
37
38 async def __aenter__(self):
39 """Return `self` upon entering the runtime context."""
40 return self
41
42 @abc.abstractmethod
43 async def __aexit__(self, exc_type, exc_value, traceback):
44 """Raise any exception triggered within the runtime context."""
45 return None
46
47 @classmethod
48 def __subclasshook__(cls, C):
49 if cls is AbstractAsyncContextManager:
50 return _collections_abc._check_methods(C, "__aenter__",
51 "__aexit__")
52 return NotImplemented
53
54
Michael Foordb3a89842010-06-30 12:17:50 +000055class ContextDecorator(object):
56 "A base class or mixin that enables context managers to work as decorators."
Nick Coghlan0ded3e32011-05-05 23:49:25 +100057
58 def _recreate_cm(self):
59 """Return a recreated instance of self.
Nick Coghlanfdc2c552011-05-06 00:02:12 +100060
Nick Coghlan3267a302012-05-21 22:54:43 +100061 Allows an otherwise one-shot context manager like
Nick Coghlan0ded3e32011-05-05 23:49:25 +100062 _GeneratorContextManager to support use as
Nick Coghlan3267a302012-05-21 22:54:43 +100063 a decorator via implicit recreation.
Nick Coghlanfdc2c552011-05-06 00:02:12 +100064
Nick Coghlan3267a302012-05-21 22:54:43 +100065 This is a private interface just for _GeneratorContextManager.
66 See issue #11647 for details.
Nick Coghlan0ded3e32011-05-05 23:49:25 +100067 """
68 return self
69
Michael Foordb3a89842010-06-30 12:17:50 +000070 def __call__(self, func):
71 @wraps(func)
72 def inner(*args, **kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +100073 with self._recreate_cm():
Michael Foordb3a89842010-06-30 12:17:50 +000074 return func(*args, **kwds)
75 return inner
76
77
Jelle Zijlstra2e624692017-04-30 18:25:58 -070078class _GeneratorContextManagerBase:
79 """Shared functionality for @contextmanager and @asynccontextmanager."""
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000080
Serhiy Storchaka101ff352015-06-28 17:06:07 +030081 def __init__(self, func, args, kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +100082 self.gen = func(*args, **kwds)
83 self.func, self.args, self.kwds = func, args, kwds
Nick Coghlan059def52013-10-26 18:08:15 +100084 # Issue 19330: ensure context manager instances have good docstrings
85 doc = getattr(func, "__doc__", None)
86 if doc is None:
87 doc = type(self).__doc__
88 self.__doc__ = doc
89 # Unfortunately, this still doesn't provide good help output when
90 # inspecting the created context manager instances, since pydoc
91 # currently bypasses the instance docstring and shows the docstring
92 # for the class instead.
93 # See http://bugs.python.org/issue19404 for more details.
Nick Coghlan0ded3e32011-05-05 23:49:25 +100094
Jelle Zijlstra2e624692017-04-30 18:25:58 -070095
96class _GeneratorContextManager(_GeneratorContextManagerBase,
97 AbstractContextManager,
98 ContextDecorator):
99 """Helper for @contextmanager decorator."""
100
Nick Coghlan0ded3e32011-05-05 23:49:25 +1000101 def _recreate_cm(self):
102 # _GCM instances are one-shot context managers, so the
103 # CM must be recreated each time a decorated function is
104 # called
Serhiy Storchaka101ff352015-06-28 17:06:07 +0300105 return self.__class__(self.func, self.args, self.kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000106
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000107 def __enter__(self):
108 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000109 return next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000110 except StopIteration:
Nick Coghlan8608d262013-10-20 00:30:51 +1000111 raise RuntimeError("generator didn't yield") from None
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000112
113 def __exit__(self, type, value, traceback):
114 if type is None:
115 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000116 next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000117 except StopIteration:
svelankar00c75e92017-04-11 05:11:13 -0400118 return False
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000119 else:
120 raise RuntimeError("generator didn't stop")
121 else:
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000122 if value is None:
123 # Need to force instantiation so we can reliably
124 # tell if we get the same exception back
125 value = type()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000126 try:
127 self.gen.throw(type, value, traceback)
Guido van Rossumb940e112007-01-10 16:19:56 +0000128 except StopIteration as exc:
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400129 # Suppress StopIteration *unless* it's the same exception that
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000130 # was passed to throw(). This prevents a StopIteration
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400131 # raised inside the "with" statement from being suppressed.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000132 return exc is not value
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400133 except RuntimeError as exc:
Nathaniel J. Smithaf88e7e2017-02-12 03:37:24 -0800134 # Don't re-raise the passed in exception. (issue27122)
Gregory P. Smithba2ecd62016-06-14 09:19:20 -0700135 if exc is value:
136 return False
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400137 # Likewise, avoid suppressing if a StopIteration exception
138 # was passed to throw() and later wrapped into a RuntimeError
139 # (see PEP 479).
svelankar00c75e92017-04-11 05:11:13 -0400140 if type is StopIteration and exc.__cause__ is value:
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400141 return False
142 raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000143 except:
144 # only re-raise if it's *not* the exception that was
145 # passed to throw(), because __exit__() must not raise
146 # an exception unless __exit__() itself failed. But throw()
147 # has to raise the exception to signal propagation, so this
148 # fixes the impedance mismatch between the throw() protocol
149 # and the __exit__() protocol.
150 #
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700151 # This cannot use 'except BaseException as exc' (as in the
152 # async implementation) to maintain compatibility with
153 # Python 2, where old-style class exceptions are not caught
154 # by 'except BaseException'.
svelankar00c75e92017-04-11 05:11:13 -0400155 if sys.exc_info()[1] is value:
156 return False
157 raise
158 raise RuntimeError("generator didn't stop after throw()")
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000159
160
Jelle Zijlstra176baa32017-12-13 17:19:17 -0800161class _AsyncGeneratorContextManager(_GeneratorContextManagerBase,
162 AbstractAsyncContextManager):
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700163 """Helper for @asynccontextmanager."""
164
165 async def __aenter__(self):
166 try:
167 return await self.gen.__anext__()
168 except StopAsyncIteration:
169 raise RuntimeError("generator didn't yield") from None
170
171 async def __aexit__(self, typ, value, traceback):
172 if typ is None:
173 try:
174 await self.gen.__anext__()
175 except StopAsyncIteration:
176 return
177 else:
178 raise RuntimeError("generator didn't stop")
179 else:
180 if value is None:
181 value = typ()
182 # See _GeneratorContextManager.__exit__ for comments on subtleties
183 # in this implementation
184 try:
185 await self.gen.athrow(typ, value, traceback)
186 raise RuntimeError("generator didn't stop after throw()")
187 except StopAsyncIteration as exc:
188 return exc is not value
189 except RuntimeError as exc:
190 if exc is value:
191 return False
192 # Avoid suppressing if a StopIteration exception
193 # was passed to throw() and later wrapped into a RuntimeError
194 # (see PEP 479 for sync generators; async generators also
195 # have this behavior). But do this only if the exception wrapped
196 # by the RuntimeError is actully Stop(Async)Iteration (see
197 # issue29692).
198 if isinstance(value, (StopIteration, StopAsyncIteration)):
199 if exc.__cause__ is value:
200 return False
201 raise
202 except BaseException as exc:
203 if exc is not value:
204 raise
205
206
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000207def contextmanager(func):
208 """@contextmanager decorator.
209
210 Typical usage:
211
212 @contextmanager
213 def some_generator(<arguments>):
214 <setup>
215 try:
216 yield <value>
217 finally:
218 <cleanup>
219
220 This makes this:
221
222 with some_generator(<arguments>) as <variable>:
223 <body>
224
225 equivalent to this:
226
227 <setup>
228 try:
229 <variable> = <value>
230 <body>
231 finally:
232 <cleanup>
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000233 """
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000234 @wraps(func)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000235 def helper(*args, **kwds):
Serhiy Storchaka101ff352015-06-28 17:06:07 +0300236 return _GeneratorContextManager(func, args, kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000237 return helper
238
239
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700240def asynccontextmanager(func):
241 """@asynccontextmanager decorator.
242
243 Typical usage:
244
245 @asynccontextmanager
246 async def some_async_generator(<arguments>):
247 <setup>
248 try:
249 yield <value>
250 finally:
251 <cleanup>
252
253 This makes this:
254
255 async with some_async_generator(<arguments>) as <variable>:
256 <body>
257
258 equivalent to this:
259
260 <setup>
261 try:
262 <variable> = <value>
263 <body>
264 finally:
265 <cleanup>
266 """
267 @wraps(func)
268 def helper(*args, **kwds):
269 return _AsyncGeneratorContextManager(func, args, kwds)
270 return helper
271
272
Brett Cannon9e080e02016-04-08 12:15:27 -0700273class closing(AbstractContextManager):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000274 """Context to automatically close something at the end of a block.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000275
276 Code like this:
277
278 with closing(<module>.open(<arguments>)) as f:
279 <block>
280
281 is equivalent to this:
282
283 f = <module>.open(<arguments>)
284 try:
285 <block>
286 finally:
287 f.close()
288
289 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000290 def __init__(self, thing):
291 self.thing = thing
292 def __enter__(self):
293 return self.thing
294 def __exit__(self, *exc_info):
295 self.thing.close()
Nick Coghlan3267a302012-05-21 22:54:43 +1000296
Berker Peksagbb44fe02014-11-28 23:28:06 +0200297
Brett Cannon9e080e02016-04-08 12:15:27 -0700298class _RedirectStream(AbstractContextManager):
Berker Peksagbb44fe02014-11-28 23:28:06 +0200299
300 _stream = None
301
302 def __init__(self, new_target):
303 self._new_target = new_target
304 # We use a list of old targets to make this CM re-entrant
305 self._old_targets = []
306
307 def __enter__(self):
308 self._old_targets.append(getattr(sys, self._stream))
309 setattr(sys, self._stream, self._new_target)
310 return self._new_target
311
312 def __exit__(self, exctype, excinst, exctb):
313 setattr(sys, self._stream, self._old_targets.pop())
314
315
316class redirect_stdout(_RedirectStream):
317 """Context manager for temporarily redirecting stdout to another file.
Nick Coghlan059def52013-10-26 18:08:15 +1000318
319 # How to send help() to stderr
320 with redirect_stdout(sys.stderr):
321 help(dir)
322
323 # How to write help() to a file
324 with open('help.txt', 'w') as f:
325 with redirect_stdout(f):
326 help(pow)
327 """
Nick Coghlan8608d262013-10-20 00:30:51 +1000328
Berker Peksagbb44fe02014-11-28 23:28:06 +0200329 _stream = "stdout"
Nick Coghlan8608d262013-10-20 00:30:51 +1000330
Nick Coghlan8608d262013-10-20 00:30:51 +1000331
Berker Peksagbb44fe02014-11-28 23:28:06 +0200332class redirect_stderr(_RedirectStream):
333 """Context manager for temporarily redirecting stderr to another file."""
334
335 _stream = "stderr"
Raymond Hettinger088cbf22013-10-10 00:46:57 -0700336
Nick Coghlan8608d262013-10-20 00:30:51 +1000337
Brett Cannon9e080e02016-04-08 12:15:27 -0700338class suppress(AbstractContextManager):
Nick Coghlan240f86d2013-10-17 23:40:57 +1000339 """Context manager to suppress specified exceptions
Raymond Hettingere318a882013-03-10 22:26:51 -0700340
Nick Coghlan8608d262013-10-20 00:30:51 +1000341 After the exception is suppressed, execution proceeds with the next
342 statement following the with statement.
Raymond Hettingere318a882013-03-10 22:26:51 -0700343
Nick Coghlan8608d262013-10-20 00:30:51 +1000344 with suppress(FileNotFoundError):
345 os.remove(somefile)
346 # Execution still resumes here if the file was already removed
Raymond Hettingere318a882013-03-10 22:26:51 -0700347 """
Nick Coghlan059def52013-10-26 18:08:15 +1000348
349 def __init__(self, *exceptions):
350 self._exceptions = exceptions
351
352 def __enter__(self):
353 pass
354
355 def __exit__(self, exctype, excinst, exctb):
356 # Unlike isinstance and issubclass, CPython exception handling
357 # currently only looks at the concrete type hierarchy (ignoring
358 # the instance and subclass checking hooks). While Guido considers
359 # that a bug rather than a feature, it's a fairly hard one to fix
360 # due to various internal implementation details. suppress provides
361 # the simpler issubclass based semantics, rather than trying to
362 # exactly reproduce the limitations of the CPython interpreter.
363 #
364 # See http://bugs.python.org/issue12029 for more details
365 return exctype is not None and issubclass(exctype, self._exceptions)
366
Nick Coghlan3267a302012-05-21 22:54:43 +1000367
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800368class _BaseExitStack:
369 """A base class for ExitStack and AsyncExitStack."""
Nick Coghlan3267a302012-05-21 22:54:43 +1000370
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800371 @staticmethod
372 def _create_exit_wrapper(cm, cm_exit):
373 def _exit_wrapper(exc_type, exc, tb):
374 return cm_exit(cm, exc_type, exc, tb)
375 return _exit_wrapper
Nick Coghlan3267a302012-05-21 22:54:43 +1000376
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800377 @staticmethod
378 def _create_cb_wrapper(callback, *args, **kwds):
379 def _exit_wrapper(exc_type, exc, tb):
380 callback(*args, **kwds)
381 return _exit_wrapper
Nick Coghlan3267a302012-05-21 22:54:43 +1000382
Nick Coghlan3267a302012-05-21 22:54:43 +1000383 def __init__(self):
384 self._exit_callbacks = deque()
385
386 def pop_all(self):
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800387 """Preserve the context stack by transferring it to a new instance."""
Nick Coghlan3267a302012-05-21 22:54:43 +1000388 new_stack = type(self)()
389 new_stack._exit_callbacks = self._exit_callbacks
390 self._exit_callbacks = deque()
391 return new_stack
392
Nick Coghlan3267a302012-05-21 22:54:43 +1000393 def push(self, exit):
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800394 """Registers a callback with the standard __exit__ method signature.
Nick Coghlan3267a302012-05-21 22:54:43 +1000395
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800396 Can suppress exceptions the same way __exit__ method can.
Nick Coghlan3267a302012-05-21 22:54:43 +1000397 Also accepts any object with an __exit__ method (registering a call
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800398 to the method instead of the object itself).
Nick Coghlan3267a302012-05-21 22:54:43 +1000399 """
400 # We use an unbound method rather than a bound method to follow
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800401 # the standard lookup behaviour for special methods.
Nick Coghlan3267a302012-05-21 22:54:43 +1000402 _cb_type = type(exit)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800403
Nick Coghlan3267a302012-05-21 22:54:43 +1000404 try:
405 exit_method = _cb_type.__exit__
406 except AttributeError:
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800407 # Not a context manager, so assume it's a callable.
408 self._push_exit_callback(exit)
Nick Coghlan3267a302012-05-21 22:54:43 +1000409 else:
410 self._push_cm_exit(exit, exit_method)
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800411 return exit # Allow use as a decorator.
Nick Coghlan3267a302012-05-21 22:54:43 +1000412
413 def enter_context(self, cm):
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800414 """Enters the supplied context manager.
Nick Coghlan3267a302012-05-21 22:54:43 +1000415
416 If successful, also pushes its __exit__ method as a callback and
417 returns the result of the __enter__ method.
418 """
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800419 # We look up the special methods on the type to match the with
420 # statement.
Nick Coghlan3267a302012-05-21 22:54:43 +1000421 _cm_type = type(cm)
422 _exit = _cm_type.__exit__
423 result = _cm_type.__enter__(cm)
424 self._push_cm_exit(cm, _exit)
425 return result
426
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800427 def callback(self, callback, *args, **kwds):
428 """Registers an arbitrary callback and arguments.
429
430 Cannot suppress exceptions.
431 """
432 _exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds)
433
434 # We changed the signature, so using @wraps is not appropriate, but
435 # setting __wrapped__ may still help with introspection.
436 _exit_wrapper.__wrapped__ = callback
437 self._push_exit_callback(_exit_wrapper)
438 return callback # Allow use as a decorator
439
440 def _push_cm_exit(self, cm, cm_exit):
441 """Helper to correctly register callbacks to __exit__ methods."""
442 _exit_wrapper = self._create_exit_wrapper(cm, cm_exit)
443 _exit_wrapper.__self__ = cm
444 self._push_exit_callback(_exit_wrapper, True)
445
446 def _push_exit_callback(self, callback, is_sync=True):
447 self._exit_callbacks.append((is_sync, callback))
448
449
450# Inspired by discussions on http://bugs.python.org/issue13585
451class ExitStack(_BaseExitStack, AbstractContextManager):
452 """Context manager for dynamic management of a stack of exit callbacks.
453
454 For example:
455 with ExitStack() as stack:
456 files = [stack.enter_context(open(fname)) for fname in filenames]
457 # All opened files will automatically be closed at the end of
458 # the with statement, even if attempts to open files later
459 # in the list raise an exception.
460 """
461
462 def __enter__(self):
463 return self
Nick Coghlan3267a302012-05-21 22:54:43 +1000464
Nick Coghlan3267a302012-05-21 22:54:43 +1000465 def __exit__(self, *exc_details):
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000466 received_exc = exc_details[0] is not None
467
Nick Coghlan77452fc2012-06-01 22:48:32 +1000468 # We manipulate the exception state so it behaves as though
469 # we were actually nesting multiple with statements
470 frame_exc = sys.exc_info()[1]
471 def _fix_exception_context(new_exc, old_exc):
Nick Coghlanadd94c92014-01-24 23:05:45 +1000472 # Context may not be correct, so find the end of the chain
Nick Coghlan77452fc2012-06-01 22:48:32 +1000473 while 1:
474 exc_context = new_exc.__context__
Nick Coghlan09761e72014-01-22 22:24:46 +1000475 if exc_context is old_exc:
476 # Context is already set correctly (see issue 20317)
477 return
478 if exc_context is None or exc_context is frame_exc:
Nick Coghlan77452fc2012-06-01 22:48:32 +1000479 break
480 new_exc = exc_context
Nick Coghlan09761e72014-01-22 22:24:46 +1000481 # Change the end of the chain to point to the exception
482 # we expect it to reference
Nick Coghlan77452fc2012-06-01 22:48:32 +1000483 new_exc.__context__ = old_exc
484
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000485 # Callbacks are invoked in LIFO order to match the behaviour of
486 # nested context managers
487 suppressed_exc = False
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000488 pending_raise = False
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000489 while self._exit_callbacks:
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800490 is_sync, cb = self._exit_callbacks.pop()
491 assert is_sync
Nick Coghlan3267a302012-05-21 22:54:43 +1000492 try:
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000493 if cb(*exc_details):
494 suppressed_exc = True
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000495 pending_raise = False
Nick Coghlan3267a302012-05-21 22:54:43 +1000496 exc_details = (None, None, None)
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000497 except:
498 new_exc_details = sys.exc_info()
Nick Coghlan77452fc2012-06-01 22:48:32 +1000499 # simulate the stack of exceptions by setting the context
500 _fix_exception_context(new_exc_details[1], exc_details[1])
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000501 pending_raise = True
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000502 exc_details = new_exc_details
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000503 if pending_raise:
504 try:
505 # bare "raise exc_details[1]" replaces our carefully
506 # set-up context
507 fixed_ctx = exc_details[1].__context__
508 raise exc_details[1]
509 except BaseException:
510 exc_details[1].__context__ = fixed_ctx
511 raise
512 return received_exc and suppressed_exc
Jesse-Bakker0784a2e2017-11-23 01:23:28 +0100513
Ilya Kulakov1aa094f2018-01-25 12:51:18 -0800514 def close(self):
515 """Immediately unwind the context stack."""
516 self.__exit__(None, None, None)
517
518
519# Inspired by discussions on https://bugs.python.org/issue29302
520class AsyncExitStack(_BaseExitStack, AbstractAsyncContextManager):
521 """Async context manager for dynamic management of a stack of exit
522 callbacks.
523
524 For example:
525 async with AsyncExitStack() as stack:
526 connections = [await stack.enter_async_context(get_connection())
527 for i in range(5)]
528 # All opened connections will automatically be released at the
529 # end of the async with statement, even if attempts to open a
530 # connection later in the list raise an exception.
531 """
532
533 @staticmethod
534 def _create_async_exit_wrapper(cm, cm_exit):
535 async def _exit_wrapper(exc_type, exc, tb):
536 return await cm_exit(cm, exc_type, exc, tb)
537 return _exit_wrapper
538
539 @staticmethod
540 def _create_async_cb_wrapper(callback, *args, **kwds):
541 async def _exit_wrapper(exc_type, exc, tb):
542 await callback(*args, **kwds)
543 return _exit_wrapper
544
545 async def enter_async_context(self, cm):
546 """Enters the supplied async context manager.
547
548 If successful, also pushes its __aexit__ method as a callback and
549 returns the result of the __aenter__ method.
550 """
551 _cm_type = type(cm)
552 _exit = _cm_type.__aexit__
553 result = await _cm_type.__aenter__(cm)
554 self._push_async_cm_exit(cm, _exit)
555 return result
556
557 def push_async_exit(self, exit):
558 """Registers a coroutine function with the standard __aexit__ method
559 signature.
560
561 Can suppress exceptions the same way __aexit__ method can.
562 Also accepts any object with an __aexit__ method (registering a call
563 to the method instead of the object itself).
564 """
565 _cb_type = type(exit)
566 try:
567 exit_method = _cb_type.__aexit__
568 except AttributeError:
569 # Not an async context manager, so assume it's a coroutine function
570 self._push_exit_callback(exit, False)
571 else:
572 self._push_async_cm_exit(exit, exit_method)
573 return exit # Allow use as a decorator
574
575 def push_async_callback(self, callback, *args, **kwds):
576 """Registers an arbitrary coroutine function and arguments.
577
578 Cannot suppress exceptions.
579 """
580 _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds)
581
582 # We changed the signature, so using @wraps is not appropriate, but
583 # setting __wrapped__ may still help with introspection.
584 _exit_wrapper.__wrapped__ = callback
585 self._push_exit_callback(_exit_wrapper, False)
586 return callback # Allow use as a decorator
587
588 async def aclose(self):
589 """Immediately unwind the context stack."""
590 await self.__aexit__(None, None, None)
591
592 def _push_async_cm_exit(self, cm, cm_exit):
593 """Helper to correctly register coroutine function to __aexit__
594 method."""
595 _exit_wrapper = self._create_async_exit_wrapper(cm, cm_exit)
596 _exit_wrapper.__self__ = cm
597 self._push_exit_callback(_exit_wrapper, False)
598
599 async def __aenter__(self):
600 return self
601
602 async def __aexit__(self, *exc_details):
603 received_exc = exc_details[0] is not None
604
605 # We manipulate the exception state so it behaves as though
606 # we were actually nesting multiple with statements
607 frame_exc = sys.exc_info()[1]
608 def _fix_exception_context(new_exc, old_exc):
609 # Context may not be correct, so find the end of the chain
610 while 1:
611 exc_context = new_exc.__context__
612 if exc_context is old_exc:
613 # Context is already set correctly (see issue 20317)
614 return
615 if exc_context is None or exc_context is frame_exc:
616 break
617 new_exc = exc_context
618 # Change the end of the chain to point to the exception
619 # we expect it to reference
620 new_exc.__context__ = old_exc
621
622 # Callbacks are invoked in LIFO order to match the behaviour of
623 # nested context managers
624 suppressed_exc = False
625 pending_raise = False
626 while self._exit_callbacks:
627 is_sync, cb = self._exit_callbacks.pop()
628 try:
629 if is_sync:
630 cb_suppress = cb(*exc_details)
631 else:
632 cb_suppress = await cb(*exc_details)
633
634 if cb_suppress:
635 suppressed_exc = True
636 pending_raise = False
637 exc_details = (None, None, None)
638 except:
639 new_exc_details = sys.exc_info()
640 # simulate the stack of exceptions by setting the context
641 _fix_exception_context(new_exc_details[1], exc_details[1])
642 pending_raise = True
643 exc_details = new_exc_details
644 if pending_raise:
645 try:
646 # bare "raise exc_details[1]" replaces our carefully
647 # set-up context
648 fixed_ctx = exc_details[1].__context__
649 raise exc_details[1]
650 except BaseException:
651 exc_details[1].__context__ = fixed_ctx
652 raise
653 return received_exc and suppressed_exc
654
Jesse-Bakker0784a2e2017-11-23 01:23:28 +0100655
656class nullcontext(AbstractContextManager):
657 """Context manager that does no additional processing.
658
659 Used as a stand-in for a normal context manager, when a particular
660 block of code is only sometimes used with a normal context manager:
661
662 cm = optional_cm if condition else nullcontext()
663 with cm:
664 # Perform operation, using optional_cm if condition is True
665 """
666
667 def __init__(self, enter_result=None):
668 self.enter_result = enter_result
669
670 def __enter__(self):
671 return self.enter_result
672
673 def __exit__(self, *excinfo):
674 pass