blob: 962cedab490eb226571ef89d40bb4b0aa8064671 [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
Jelle Zijlstra2e624692017-04-30 18:25:58 -07008__all__ = ["asynccontextmanager", "contextmanager", "closing",
9 "AbstractContextManager", "ContextDecorator", "ExitStack",
10 "redirect_stdout", "redirect_stderr", "suppress"]
Brett Cannon9e080e02016-04-08 12:15:27 -070011
12
13class AbstractContextManager(abc.ABC):
14
15 """An abstract base class for context managers."""
16
17 def __enter__(self):
18 """Return `self` upon entering the runtime context."""
19 return self
20
21 @abc.abstractmethod
22 def __exit__(self, exc_type, exc_value, traceback):
23 """Raise any exception triggered within the runtime context."""
24 return None
25
26 @classmethod
27 def __subclasshook__(cls, C):
28 if cls is AbstractContextManager:
Jelle Zijlstra57161aa2017-06-09 08:21:47 -070029 return _collections_abc._check_methods(C, "__enter__", "__exit__")
Brett Cannon9e080e02016-04-08 12:15:27 -070030 return NotImplemented
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000031
Michael Foordb3a89842010-06-30 12:17:50 +000032
33class ContextDecorator(object):
34 "A base class or mixin that enables context managers to work as decorators."
Nick Coghlan0ded3e32011-05-05 23:49:25 +100035
36 def _recreate_cm(self):
37 """Return a recreated instance of self.
Nick Coghlanfdc2c552011-05-06 00:02:12 +100038
Nick Coghlan3267a302012-05-21 22:54:43 +100039 Allows an otherwise one-shot context manager like
Nick Coghlan0ded3e32011-05-05 23:49:25 +100040 _GeneratorContextManager to support use as
Nick Coghlan3267a302012-05-21 22:54:43 +100041 a decorator via implicit recreation.
Nick Coghlanfdc2c552011-05-06 00:02:12 +100042
Nick Coghlan3267a302012-05-21 22:54:43 +100043 This is a private interface just for _GeneratorContextManager.
44 See issue #11647 for details.
Nick Coghlan0ded3e32011-05-05 23:49:25 +100045 """
46 return self
47
Michael Foordb3a89842010-06-30 12:17:50 +000048 def __call__(self, func):
49 @wraps(func)
50 def inner(*args, **kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +100051 with self._recreate_cm():
Michael Foordb3a89842010-06-30 12:17:50 +000052 return func(*args, **kwds)
53 return inner
54
55
Jelle Zijlstra2e624692017-04-30 18:25:58 -070056class _GeneratorContextManagerBase:
57 """Shared functionality for @contextmanager and @asynccontextmanager."""
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000058
Serhiy Storchaka101ff352015-06-28 17:06:07 +030059 def __init__(self, func, args, kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +100060 self.gen = func(*args, **kwds)
61 self.func, self.args, self.kwds = func, args, kwds
Nick Coghlan059def52013-10-26 18:08:15 +100062 # Issue 19330: ensure context manager instances have good docstrings
63 doc = getattr(func, "__doc__", None)
64 if doc is None:
65 doc = type(self).__doc__
66 self.__doc__ = doc
67 # Unfortunately, this still doesn't provide good help output when
68 # inspecting the created context manager instances, since pydoc
69 # currently bypasses the instance docstring and shows the docstring
70 # for the class instead.
71 # See http://bugs.python.org/issue19404 for more details.
Nick Coghlan0ded3e32011-05-05 23:49:25 +100072
Jelle Zijlstra2e624692017-04-30 18:25:58 -070073
74class _GeneratorContextManager(_GeneratorContextManagerBase,
75 AbstractContextManager,
76 ContextDecorator):
77 """Helper for @contextmanager decorator."""
78
Nick Coghlan0ded3e32011-05-05 23:49:25 +100079 def _recreate_cm(self):
80 # _GCM instances are one-shot context managers, so the
81 # CM must be recreated each time a decorated function is
82 # called
Serhiy Storchaka101ff352015-06-28 17:06:07 +030083 return self.__class__(self.func, self.args, self.kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000084
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000085 def __enter__(self):
86 try:
Georg Brandla18af4e2007-04-21 15:47:16 +000087 return next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000088 except StopIteration:
Nick Coghlan8608d262013-10-20 00:30:51 +100089 raise RuntimeError("generator didn't yield") from None
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000090
91 def __exit__(self, type, value, traceback):
92 if type is None:
93 try:
Georg Brandla18af4e2007-04-21 15:47:16 +000094 next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000095 except StopIteration:
svelankar00c75e92017-04-11 05:11:13 -040096 return False
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000097 else:
98 raise RuntimeError("generator didn't stop")
99 else:
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000100 if value is None:
101 # Need to force instantiation so we can reliably
102 # tell if we get the same exception back
103 value = type()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000104 try:
105 self.gen.throw(type, value, traceback)
Guido van Rossumb940e112007-01-10 16:19:56 +0000106 except StopIteration as exc:
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400107 # Suppress StopIteration *unless* it's the same exception that
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000108 # was passed to throw(). This prevents a StopIteration
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400109 # raised inside the "with" statement from being suppressed.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000110 return exc is not value
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400111 except RuntimeError as exc:
Nathaniel J. Smithaf88e7e2017-02-12 03:37:24 -0800112 # Don't re-raise the passed in exception. (issue27122)
Gregory P. Smithba2ecd62016-06-14 09:19:20 -0700113 if exc is value:
114 return False
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400115 # Likewise, avoid suppressing if a StopIteration exception
116 # was passed to throw() and later wrapped into a RuntimeError
117 # (see PEP 479).
svelankar00c75e92017-04-11 05:11:13 -0400118 if type is StopIteration and exc.__cause__ is value:
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400119 return False
120 raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000121 except:
122 # only re-raise if it's *not* the exception that was
123 # passed to throw(), because __exit__() must not raise
124 # an exception unless __exit__() itself failed. But throw()
125 # has to raise the exception to signal propagation, so this
126 # fixes the impedance mismatch between the throw() protocol
127 # and the __exit__() protocol.
128 #
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700129 # This cannot use 'except BaseException as exc' (as in the
130 # async implementation) to maintain compatibility with
131 # Python 2, where old-style class exceptions are not caught
132 # by 'except BaseException'.
svelankar00c75e92017-04-11 05:11:13 -0400133 if sys.exc_info()[1] is value:
134 return False
135 raise
136 raise RuntimeError("generator didn't stop after throw()")
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000137
138
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700139class _AsyncGeneratorContextManager(_GeneratorContextManagerBase):
140 """Helper for @asynccontextmanager."""
141
142 async def __aenter__(self):
143 try:
144 return await self.gen.__anext__()
145 except StopAsyncIteration:
146 raise RuntimeError("generator didn't yield") from None
147
148 async def __aexit__(self, typ, value, traceback):
149 if typ is None:
150 try:
151 await self.gen.__anext__()
152 except StopAsyncIteration:
153 return
154 else:
155 raise RuntimeError("generator didn't stop")
156 else:
157 if value is None:
158 value = typ()
159 # See _GeneratorContextManager.__exit__ for comments on subtleties
160 # in this implementation
161 try:
162 await self.gen.athrow(typ, value, traceback)
163 raise RuntimeError("generator didn't stop after throw()")
164 except StopAsyncIteration as exc:
165 return exc is not value
166 except RuntimeError as exc:
167 if exc is value:
168 return False
169 # Avoid suppressing if a StopIteration exception
170 # was passed to throw() and later wrapped into a RuntimeError
171 # (see PEP 479 for sync generators; async generators also
172 # have this behavior). But do this only if the exception wrapped
173 # by the RuntimeError is actully Stop(Async)Iteration (see
174 # issue29692).
175 if isinstance(value, (StopIteration, StopAsyncIteration)):
176 if exc.__cause__ is value:
177 return False
178 raise
179 except BaseException as exc:
180 if exc is not value:
181 raise
182
183
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000184def contextmanager(func):
185 """@contextmanager decorator.
186
187 Typical usage:
188
189 @contextmanager
190 def some_generator(<arguments>):
191 <setup>
192 try:
193 yield <value>
194 finally:
195 <cleanup>
196
197 This makes this:
198
199 with some_generator(<arguments>) as <variable>:
200 <body>
201
202 equivalent to this:
203
204 <setup>
205 try:
206 <variable> = <value>
207 <body>
208 finally:
209 <cleanup>
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000210 """
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000211 @wraps(func)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000212 def helper(*args, **kwds):
Serhiy Storchaka101ff352015-06-28 17:06:07 +0300213 return _GeneratorContextManager(func, args, kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000214 return helper
215
216
Jelle Zijlstra2e624692017-04-30 18:25:58 -0700217def asynccontextmanager(func):
218 """@asynccontextmanager decorator.
219
220 Typical usage:
221
222 @asynccontextmanager
223 async def some_async_generator(<arguments>):
224 <setup>
225 try:
226 yield <value>
227 finally:
228 <cleanup>
229
230 This makes this:
231
232 async with some_async_generator(<arguments>) as <variable>:
233 <body>
234
235 equivalent to this:
236
237 <setup>
238 try:
239 <variable> = <value>
240 <body>
241 finally:
242 <cleanup>
243 """
244 @wraps(func)
245 def helper(*args, **kwds):
246 return _AsyncGeneratorContextManager(func, args, kwds)
247 return helper
248
249
Brett Cannon9e080e02016-04-08 12:15:27 -0700250class closing(AbstractContextManager):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000251 """Context to automatically close something at the end of a block.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000252
253 Code like this:
254
255 with closing(<module>.open(<arguments>)) as f:
256 <block>
257
258 is equivalent to this:
259
260 f = <module>.open(<arguments>)
261 try:
262 <block>
263 finally:
264 f.close()
265
266 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000267 def __init__(self, thing):
268 self.thing = thing
269 def __enter__(self):
270 return self.thing
271 def __exit__(self, *exc_info):
272 self.thing.close()
Nick Coghlan3267a302012-05-21 22:54:43 +1000273
Berker Peksagbb44fe02014-11-28 23:28:06 +0200274
Brett Cannon9e080e02016-04-08 12:15:27 -0700275class _RedirectStream(AbstractContextManager):
Berker Peksagbb44fe02014-11-28 23:28:06 +0200276
277 _stream = None
278
279 def __init__(self, new_target):
280 self._new_target = new_target
281 # We use a list of old targets to make this CM re-entrant
282 self._old_targets = []
283
284 def __enter__(self):
285 self._old_targets.append(getattr(sys, self._stream))
286 setattr(sys, self._stream, self._new_target)
287 return self._new_target
288
289 def __exit__(self, exctype, excinst, exctb):
290 setattr(sys, self._stream, self._old_targets.pop())
291
292
293class redirect_stdout(_RedirectStream):
294 """Context manager for temporarily redirecting stdout to another file.
Nick Coghlan059def52013-10-26 18:08:15 +1000295
296 # How to send help() to stderr
297 with redirect_stdout(sys.stderr):
298 help(dir)
299
300 # How to write help() to a file
301 with open('help.txt', 'w') as f:
302 with redirect_stdout(f):
303 help(pow)
304 """
Nick Coghlan8608d262013-10-20 00:30:51 +1000305
Berker Peksagbb44fe02014-11-28 23:28:06 +0200306 _stream = "stdout"
Nick Coghlan8608d262013-10-20 00:30:51 +1000307
Nick Coghlan8608d262013-10-20 00:30:51 +1000308
Berker Peksagbb44fe02014-11-28 23:28:06 +0200309class redirect_stderr(_RedirectStream):
310 """Context manager for temporarily redirecting stderr to another file."""
311
312 _stream = "stderr"
Raymond Hettinger088cbf22013-10-10 00:46:57 -0700313
Nick Coghlan8608d262013-10-20 00:30:51 +1000314
Brett Cannon9e080e02016-04-08 12:15:27 -0700315class suppress(AbstractContextManager):
Nick Coghlan240f86d2013-10-17 23:40:57 +1000316 """Context manager to suppress specified exceptions
Raymond Hettingere318a882013-03-10 22:26:51 -0700317
Nick Coghlan8608d262013-10-20 00:30:51 +1000318 After the exception is suppressed, execution proceeds with the next
319 statement following the with statement.
Raymond Hettingere318a882013-03-10 22:26:51 -0700320
Nick Coghlan8608d262013-10-20 00:30:51 +1000321 with suppress(FileNotFoundError):
322 os.remove(somefile)
323 # Execution still resumes here if the file was already removed
Raymond Hettingere318a882013-03-10 22:26:51 -0700324 """
Nick Coghlan059def52013-10-26 18:08:15 +1000325
326 def __init__(self, *exceptions):
327 self._exceptions = exceptions
328
329 def __enter__(self):
330 pass
331
332 def __exit__(self, exctype, excinst, exctb):
333 # Unlike isinstance and issubclass, CPython exception handling
334 # currently only looks at the concrete type hierarchy (ignoring
335 # the instance and subclass checking hooks). While Guido considers
336 # that a bug rather than a feature, it's a fairly hard one to fix
337 # due to various internal implementation details. suppress provides
338 # the simpler issubclass based semantics, rather than trying to
339 # exactly reproduce the limitations of the CPython interpreter.
340 #
341 # See http://bugs.python.org/issue12029 for more details
342 return exctype is not None and issubclass(exctype, self._exceptions)
343
Nick Coghlan3267a302012-05-21 22:54:43 +1000344
345# Inspired by discussions on http://bugs.python.org/issue13585
Brett Cannon9e080e02016-04-08 12:15:27 -0700346class ExitStack(AbstractContextManager):
Nick Coghlan3267a302012-05-21 22:54:43 +1000347 """Context manager for dynamic management of a stack of exit callbacks
348
349 For example:
350
351 with ExitStack() as stack:
352 files = [stack.enter_context(open(fname)) for fname in filenames]
353 # All opened files will automatically be closed at the end of
354 # the with statement, even if attempts to open files later
Andrew Svetlov5b898402012-12-18 21:26:36 +0200355 # in the list raise an exception
Nick Coghlan3267a302012-05-21 22:54:43 +1000356
357 """
358 def __init__(self):
359 self._exit_callbacks = deque()
360
361 def pop_all(self):
362 """Preserve the context stack by transferring it to a new instance"""
363 new_stack = type(self)()
364 new_stack._exit_callbacks = self._exit_callbacks
365 self._exit_callbacks = deque()
366 return new_stack
367
368 def _push_cm_exit(self, cm, cm_exit):
369 """Helper to correctly register callbacks to __exit__ methods"""
370 def _exit_wrapper(*exc_details):
371 return cm_exit(cm, *exc_details)
372 _exit_wrapper.__self__ = cm
373 self.push(_exit_wrapper)
374
375 def push(self, exit):
376 """Registers a callback with the standard __exit__ method signature
377
378 Can suppress exceptions the same way __exit__ methods can.
379
380 Also accepts any object with an __exit__ method (registering a call
381 to the method instead of the object itself)
382 """
383 # We use an unbound method rather than a bound method to follow
384 # the standard lookup behaviour for special methods
385 _cb_type = type(exit)
386 try:
387 exit_method = _cb_type.__exit__
388 except AttributeError:
389 # Not a context manager, so assume its a callable
390 self._exit_callbacks.append(exit)
391 else:
392 self._push_cm_exit(exit, exit_method)
393 return exit # Allow use as a decorator
394
395 def callback(self, callback, *args, **kwds):
396 """Registers an arbitrary callback and arguments.
397
398 Cannot suppress exceptions.
399 """
400 def _exit_wrapper(exc_type, exc, tb):
401 callback(*args, **kwds)
402 # We changed the signature, so using @wraps is not appropriate, but
403 # setting __wrapped__ may still help with introspection
404 _exit_wrapper.__wrapped__ = callback
405 self.push(_exit_wrapper)
406 return callback # Allow use as a decorator
407
408 def enter_context(self, cm):
409 """Enters the supplied context manager
410
411 If successful, also pushes its __exit__ method as a callback and
412 returns the result of the __enter__ method.
413 """
414 # We look up the special methods on the type to match the with statement
415 _cm_type = type(cm)
416 _exit = _cm_type.__exit__
417 result = _cm_type.__enter__(cm)
418 self._push_cm_exit(cm, _exit)
419 return result
420
421 def close(self):
422 """Immediately unwind the context stack"""
423 self.__exit__(None, None, None)
424
Nick Coghlan3267a302012-05-21 22:54:43 +1000425 def __exit__(self, *exc_details):
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000426 received_exc = exc_details[0] is not None
427
Nick Coghlan77452fc2012-06-01 22:48:32 +1000428 # We manipulate the exception state so it behaves as though
429 # we were actually nesting multiple with statements
430 frame_exc = sys.exc_info()[1]
431 def _fix_exception_context(new_exc, old_exc):
Nick Coghlanadd94c92014-01-24 23:05:45 +1000432 # Context may not be correct, so find the end of the chain
Nick Coghlan77452fc2012-06-01 22:48:32 +1000433 while 1:
434 exc_context = new_exc.__context__
Nick Coghlan09761e72014-01-22 22:24:46 +1000435 if exc_context is old_exc:
436 # Context is already set correctly (see issue 20317)
437 return
438 if exc_context is None or exc_context is frame_exc:
Nick Coghlan77452fc2012-06-01 22:48:32 +1000439 break
440 new_exc = exc_context
Nick Coghlan09761e72014-01-22 22:24:46 +1000441 # Change the end of the chain to point to the exception
442 # we expect it to reference
Nick Coghlan77452fc2012-06-01 22:48:32 +1000443 new_exc.__context__ = old_exc
444
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000445 # Callbacks are invoked in LIFO order to match the behaviour of
446 # nested context managers
447 suppressed_exc = False
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000448 pending_raise = False
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000449 while self._exit_callbacks:
450 cb = self._exit_callbacks.pop()
Nick Coghlan3267a302012-05-21 22:54:43 +1000451 try:
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000452 if cb(*exc_details):
453 suppressed_exc = True
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000454 pending_raise = False
Nick Coghlan3267a302012-05-21 22:54:43 +1000455 exc_details = (None, None, None)
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000456 except:
457 new_exc_details = sys.exc_info()
Nick Coghlan77452fc2012-06-01 22:48:32 +1000458 # simulate the stack of exceptions by setting the context
459 _fix_exception_context(new_exc_details[1], exc_details[1])
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000460 pending_raise = True
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000461 exc_details = new_exc_details
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000462 if pending_raise:
463 try:
464 # bare "raise exc_details[1]" replaces our carefully
465 # set-up context
466 fixed_ctx = exc_details[1].__context__
467 raise exc_details[1]
468 except BaseException:
469 exc_details[1].__context__ = fixed_ctx
470 raise
471 return received_exc and suppressed_exc