blob: 6cf112af0d3e326d1f014d87ea118b2352a50bae [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
Nick Coghlan3267a302012-05-21 22:54:43 +10004from collections import deque
Christian Heimes81ee3ef2008-05-04 22:42:01 +00005from functools import wraps
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00006
Brett Cannon9e080e02016-04-08 12:15:27 -07007__all__ = ["contextmanager", "closing", "AbstractContextManager",
8 "ContextDecorator", "ExitStack", "redirect_stdout",
9 "redirect_stderr", "suppress"]
10
11
12class 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 Cannon8bd092b2016-04-08 12:16:16 -070030 return True
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
34class ContextDecorator(object):
35 "A base class or mixin that enables context managers to work as decorators."
Nick Coghlan0ded3e32011-05-05 23:49:25 +100036
37 def _recreate_cm(self):
38 """Return a recreated instance of self.
Nick Coghlanfdc2c552011-05-06 00:02:12 +100039
Nick Coghlan3267a302012-05-21 22:54:43 +100040 Allows an otherwise one-shot context manager like
Nick Coghlan0ded3e32011-05-05 23:49:25 +100041 _GeneratorContextManager to support use as
Nick Coghlan3267a302012-05-21 22:54:43 +100042 a decorator via implicit recreation.
Nick Coghlanfdc2c552011-05-06 00:02:12 +100043
Nick Coghlan3267a302012-05-21 22:54:43 +100044 This is a private interface just for _GeneratorContextManager.
45 See issue #11647 for details.
Nick Coghlan0ded3e32011-05-05 23:49:25 +100046 """
47 return self
48
Michael Foordb3a89842010-06-30 12:17:50 +000049 def __call__(self, func):
50 @wraps(func)
51 def inner(*args, **kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +100052 with self._recreate_cm():
Michael Foordb3a89842010-06-30 12:17:50 +000053 return func(*args, **kwds)
54 return inner
55
56
Brett Cannon9e080e02016-04-08 12:15:27 -070057class _GeneratorContextManager(ContextDecorator, AbstractContextManager):
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000058 """Helper for @contextmanager decorator."""
59
Serhiy Storchaka101ff352015-06-28 17:06:07 +030060 def __init__(self, func, args, kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +100061 self.gen = func(*args, **kwds)
62 self.func, self.args, self.kwds = func, args, kwds
Nick Coghlan059def52013-10-26 18:08:15 +100063 # 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 Coghlan0ded3e32011-05-05 23:49:25 +100073
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 Storchaka101ff352015-06-28 17:06:07 +030078 return self.__class__(self.func, self.args, self.kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000079
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000080 def __enter__(self):
81 try:
Georg Brandla18af4e2007-04-21 15:47:16 +000082 return next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000083 except StopIteration:
Nick Coghlan8608d262013-10-20 00:30:51 +100084 raise RuntimeError("generator didn't yield") from None
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000085
86 def __exit__(self, type, value, traceback):
87 if type is None:
88 try:
Georg Brandla18af4e2007-04-21 15:47:16 +000089 next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000090 except StopIteration:
91 return
92 else:
93 raise RuntimeError("generator didn't stop")
94 else:
Guido van Rossum2cc30da2007-11-02 23:46:40 +000095 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 Rossum1a5e21e2006-02-28 21:57:43 +000099 try:
100 self.gen.throw(type, value, traceback)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000101 raise RuntimeError("generator didn't stop after throw()")
Guido van Rossumb940e112007-01-10 16:19:56 +0000102 except StopIteration as exc:
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400103 # Suppress StopIteration *unless* it's the same exception that
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000104 # was passed to throw(). This prevents a StopIteration
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400105 # raised inside the "with" statement from being suppressed.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000106 return exc is not value
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400107 except RuntimeError as exc:
108 # Likewise, avoid suppressing if a StopIteration exception
109 # was passed to throw() and later wrapped into a RuntimeError
110 # (see PEP 479).
111 if exc.__cause__ is value:
112 return False
113 raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000114 except:
115 # only re-raise if it's *not* the exception that was
116 # passed to throw(), because __exit__() must not raise
117 # an exception unless __exit__() itself failed. But throw()
118 # has to raise the exception to signal propagation, so this
119 # fixes the impedance mismatch between the throw() protocol
120 # and the __exit__() protocol.
121 #
122 if sys.exc_info()[1] is not value:
123 raise
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000124
125
126def contextmanager(func):
127 """@contextmanager decorator.
128
129 Typical usage:
130
131 @contextmanager
132 def some_generator(<arguments>):
133 <setup>
134 try:
135 yield <value>
136 finally:
137 <cleanup>
138
139 This makes this:
140
141 with some_generator(<arguments>) as <variable>:
142 <body>
143
144 equivalent to this:
145
146 <setup>
147 try:
148 <variable> = <value>
149 <body>
150 finally:
151 <cleanup>
152
153 """
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000154 @wraps(func)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000155 def helper(*args, **kwds):
Serhiy Storchaka101ff352015-06-28 17:06:07 +0300156 return _GeneratorContextManager(func, args, kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000157 return helper
158
159
Brett Cannon9e080e02016-04-08 12:15:27 -0700160class closing(AbstractContextManager):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000161 """Context to automatically close something at the end of a block.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000162
163 Code like this:
164
165 with closing(<module>.open(<arguments>)) as f:
166 <block>
167
168 is equivalent to this:
169
170 f = <module>.open(<arguments>)
171 try:
172 <block>
173 finally:
174 f.close()
175
176 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000177 def __init__(self, thing):
178 self.thing = thing
179 def __enter__(self):
180 return self.thing
181 def __exit__(self, *exc_info):
182 self.thing.close()
Nick Coghlan3267a302012-05-21 22:54:43 +1000183
Berker Peksagbb44fe02014-11-28 23:28:06 +0200184
Brett Cannon9e080e02016-04-08 12:15:27 -0700185class _RedirectStream(AbstractContextManager):
Berker Peksagbb44fe02014-11-28 23:28:06 +0200186
187 _stream = None
188
189 def __init__(self, new_target):
190 self._new_target = new_target
191 # We use a list of old targets to make this CM re-entrant
192 self._old_targets = []
193
194 def __enter__(self):
195 self._old_targets.append(getattr(sys, self._stream))
196 setattr(sys, self._stream, self._new_target)
197 return self._new_target
198
199 def __exit__(self, exctype, excinst, exctb):
200 setattr(sys, self._stream, self._old_targets.pop())
201
202
203class redirect_stdout(_RedirectStream):
204 """Context manager for temporarily redirecting stdout to another file.
Nick Coghlan059def52013-10-26 18:08:15 +1000205
206 # How to send help() to stderr
207 with redirect_stdout(sys.stderr):
208 help(dir)
209
210 # How to write help() to a file
211 with open('help.txt', 'w') as f:
212 with redirect_stdout(f):
213 help(pow)
214 """
Nick Coghlan8608d262013-10-20 00:30:51 +1000215
Berker Peksagbb44fe02014-11-28 23:28:06 +0200216 _stream = "stdout"
Nick Coghlan8608d262013-10-20 00:30:51 +1000217
Nick Coghlan8608d262013-10-20 00:30:51 +1000218
Berker Peksagbb44fe02014-11-28 23:28:06 +0200219class redirect_stderr(_RedirectStream):
220 """Context manager for temporarily redirecting stderr to another file."""
221
222 _stream = "stderr"
Raymond Hettinger088cbf22013-10-10 00:46:57 -0700223
Nick Coghlan8608d262013-10-20 00:30:51 +1000224
Brett Cannon9e080e02016-04-08 12:15:27 -0700225class suppress(AbstractContextManager):
Nick Coghlan240f86d2013-10-17 23:40:57 +1000226 """Context manager to suppress specified exceptions
Raymond Hettingere318a882013-03-10 22:26:51 -0700227
Nick Coghlan8608d262013-10-20 00:30:51 +1000228 After the exception is suppressed, execution proceeds with the next
229 statement following the with statement.
Raymond Hettingere318a882013-03-10 22:26:51 -0700230
Nick Coghlan8608d262013-10-20 00:30:51 +1000231 with suppress(FileNotFoundError):
232 os.remove(somefile)
233 # Execution still resumes here if the file was already removed
Raymond Hettingere318a882013-03-10 22:26:51 -0700234 """
Nick Coghlan059def52013-10-26 18:08:15 +1000235
236 def __init__(self, *exceptions):
237 self._exceptions = exceptions
238
239 def __enter__(self):
240 pass
241
242 def __exit__(self, exctype, excinst, exctb):
243 # Unlike isinstance and issubclass, CPython exception handling
244 # currently only looks at the concrete type hierarchy (ignoring
245 # the instance and subclass checking hooks). While Guido considers
246 # that a bug rather than a feature, it's a fairly hard one to fix
247 # due to various internal implementation details. suppress provides
248 # the simpler issubclass based semantics, rather than trying to
249 # exactly reproduce the limitations of the CPython interpreter.
250 #
251 # See http://bugs.python.org/issue12029 for more details
252 return exctype is not None and issubclass(exctype, self._exceptions)
253
Nick Coghlan3267a302012-05-21 22:54:43 +1000254
255# Inspired by discussions on http://bugs.python.org/issue13585
Brett Cannon9e080e02016-04-08 12:15:27 -0700256class ExitStack(AbstractContextManager):
Nick Coghlan3267a302012-05-21 22:54:43 +1000257 """Context manager for dynamic management of a stack of exit callbacks
258
259 For example:
260
261 with ExitStack() as stack:
262 files = [stack.enter_context(open(fname)) for fname in filenames]
263 # All opened files will automatically be closed at the end of
264 # the with statement, even if attempts to open files later
Andrew Svetlov5b898402012-12-18 21:26:36 +0200265 # in the list raise an exception
Nick Coghlan3267a302012-05-21 22:54:43 +1000266
267 """
268 def __init__(self):
269 self._exit_callbacks = deque()
270
271 def pop_all(self):
272 """Preserve the context stack by transferring it to a new instance"""
273 new_stack = type(self)()
274 new_stack._exit_callbacks = self._exit_callbacks
275 self._exit_callbacks = deque()
276 return new_stack
277
278 def _push_cm_exit(self, cm, cm_exit):
279 """Helper to correctly register callbacks to __exit__ methods"""
280 def _exit_wrapper(*exc_details):
281 return cm_exit(cm, *exc_details)
282 _exit_wrapper.__self__ = cm
283 self.push(_exit_wrapper)
284
285 def push(self, exit):
286 """Registers a callback with the standard __exit__ method signature
287
288 Can suppress exceptions the same way __exit__ methods can.
289
290 Also accepts any object with an __exit__ method (registering a call
291 to the method instead of the object itself)
292 """
293 # We use an unbound method rather than a bound method to follow
294 # the standard lookup behaviour for special methods
295 _cb_type = type(exit)
296 try:
297 exit_method = _cb_type.__exit__
298 except AttributeError:
299 # Not a context manager, so assume its a callable
300 self._exit_callbacks.append(exit)
301 else:
302 self._push_cm_exit(exit, exit_method)
303 return exit # Allow use as a decorator
304
305 def callback(self, callback, *args, **kwds):
306 """Registers an arbitrary callback and arguments.
307
308 Cannot suppress exceptions.
309 """
310 def _exit_wrapper(exc_type, exc, tb):
311 callback(*args, **kwds)
312 # We changed the signature, so using @wraps is not appropriate, but
313 # setting __wrapped__ may still help with introspection
314 _exit_wrapper.__wrapped__ = callback
315 self.push(_exit_wrapper)
316 return callback # Allow use as a decorator
317
318 def enter_context(self, cm):
319 """Enters the supplied context manager
320
321 If successful, also pushes its __exit__ method as a callback and
322 returns the result of the __enter__ method.
323 """
324 # We look up the special methods on the type to match the with statement
325 _cm_type = type(cm)
326 _exit = _cm_type.__exit__
327 result = _cm_type.__enter__(cm)
328 self._push_cm_exit(cm, _exit)
329 return result
330
331 def close(self):
332 """Immediately unwind the context stack"""
333 self.__exit__(None, None, None)
334
Nick Coghlan3267a302012-05-21 22:54:43 +1000335 def __exit__(self, *exc_details):
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000336 received_exc = exc_details[0] is not None
337
Nick Coghlan77452fc2012-06-01 22:48:32 +1000338 # We manipulate the exception state so it behaves as though
339 # we were actually nesting multiple with statements
340 frame_exc = sys.exc_info()[1]
341 def _fix_exception_context(new_exc, old_exc):
Nick Coghlanadd94c92014-01-24 23:05:45 +1000342 # Context may not be correct, so find the end of the chain
Nick Coghlan77452fc2012-06-01 22:48:32 +1000343 while 1:
344 exc_context = new_exc.__context__
Nick Coghlan09761e72014-01-22 22:24:46 +1000345 if exc_context is old_exc:
346 # Context is already set correctly (see issue 20317)
347 return
348 if exc_context is None or exc_context is frame_exc:
Nick Coghlan77452fc2012-06-01 22:48:32 +1000349 break
350 new_exc = exc_context
Nick Coghlan09761e72014-01-22 22:24:46 +1000351 # Change the end of the chain to point to the exception
352 # we expect it to reference
Nick Coghlan77452fc2012-06-01 22:48:32 +1000353 new_exc.__context__ = old_exc
354
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000355 # Callbacks are invoked in LIFO order to match the behaviour of
356 # nested context managers
357 suppressed_exc = False
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000358 pending_raise = False
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000359 while self._exit_callbacks:
360 cb = self._exit_callbacks.pop()
Nick Coghlan3267a302012-05-21 22:54:43 +1000361 try:
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000362 if cb(*exc_details):
363 suppressed_exc = True
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000364 pending_raise = False
Nick Coghlan3267a302012-05-21 22:54:43 +1000365 exc_details = (None, None, None)
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000366 except:
367 new_exc_details = sys.exc_info()
Nick Coghlan77452fc2012-06-01 22:48:32 +1000368 # simulate the stack of exceptions by setting the context
369 _fix_exception_context(new_exc_details[1], exc_details[1])
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000370 pending_raise = True
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000371 exc_details = new_exc_details
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000372 if pending_raise:
373 try:
374 # bare "raise exc_details[1]" replaces our carefully
375 # set-up context
376 fixed_ctx = exc_details[1].__context__
377 raise exc_details[1]
378 except BaseException:
379 exc_details[1].__context__ = fixed_ctx
380 raise
381 return received_exc and suppressed_exc