blob: d44edd6e198ad94b09d173088f473126287ed8dc [file] [log] [blame]
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001"""Utilities for with-statement contexts. See PEP 343."""
2
3import 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
Raymond Hettinger088cbf22013-10-10 00:46:57 -07007__all__ = ["contextmanager", "closing", "ContextDecorator", "ExitStack",
Berker Peksagbb44fe02014-11-28 23:28:06 +02008 "redirect_stdout", "redirect_stderr", "suppress"]
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00009
Michael Foordb3a89842010-06-30 12:17:50 +000010
11class ContextDecorator(object):
12 "A base class or mixin that enables context managers to work as decorators."
Nick Coghlan0ded3e32011-05-05 23:49:25 +100013
14 def _recreate_cm(self):
15 """Return a recreated instance of self.
Nick Coghlanfdc2c552011-05-06 00:02:12 +100016
Nick Coghlan3267a302012-05-21 22:54:43 +100017 Allows an otherwise one-shot context manager like
Nick Coghlan0ded3e32011-05-05 23:49:25 +100018 _GeneratorContextManager to support use as
Nick Coghlan3267a302012-05-21 22:54:43 +100019 a decorator via implicit recreation.
Nick Coghlanfdc2c552011-05-06 00:02:12 +100020
Nick Coghlan3267a302012-05-21 22:54:43 +100021 This is a private interface just for _GeneratorContextManager.
22 See issue #11647 for details.
Nick Coghlan0ded3e32011-05-05 23:49:25 +100023 """
24 return self
25
Michael Foordb3a89842010-06-30 12:17:50 +000026 def __call__(self, func):
27 @wraps(func)
28 def inner(*args, **kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +100029 with self._recreate_cm():
Michael Foordb3a89842010-06-30 12:17:50 +000030 return func(*args, **kwds)
31 return inner
32
33
Antoine Pitrou67b212e2011-01-08 09:55:31 +000034class _GeneratorContextManager(ContextDecorator):
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000035 """Helper for @contextmanager decorator."""
36
Serhiy Storchaka101ff352015-06-28 17:06:07 +030037 def __init__(self, func, args, kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +100038 self.gen = func(*args, **kwds)
39 self.func, self.args, self.kwds = func, args, kwds
Nick Coghlan059def52013-10-26 18:08:15 +100040 # Issue 19330: ensure context manager instances have good docstrings
41 doc = getattr(func, "__doc__", None)
42 if doc is None:
43 doc = type(self).__doc__
44 self.__doc__ = doc
45 # Unfortunately, this still doesn't provide good help output when
46 # inspecting the created context manager instances, since pydoc
47 # currently bypasses the instance docstring and shows the docstring
48 # for the class instead.
49 # See http://bugs.python.org/issue19404 for more details.
Nick Coghlan0ded3e32011-05-05 23:49:25 +100050
51 def _recreate_cm(self):
52 # _GCM instances are one-shot context managers, so the
53 # CM must be recreated each time a decorated function is
54 # called
Serhiy Storchaka101ff352015-06-28 17:06:07 +030055 return self.__class__(self.func, self.args, self.kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000056
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000057 def __enter__(self):
58 try:
Georg Brandla18af4e2007-04-21 15:47:16 +000059 return next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000060 except StopIteration:
Nick Coghlan8608d262013-10-20 00:30:51 +100061 raise RuntimeError("generator didn't yield") from None
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000062
63 def __exit__(self, type, value, traceback):
64 if type is None:
65 try:
Georg Brandla18af4e2007-04-21 15:47:16 +000066 next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000067 except StopIteration:
68 return
69 else:
70 raise RuntimeError("generator didn't stop")
71 else:
Guido van Rossum2cc30da2007-11-02 23:46:40 +000072 if value is None:
73 # Need to force instantiation so we can reliably
74 # tell if we get the same exception back
75 value = type()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000076 try:
77 self.gen.throw(type, value, traceback)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000078 raise RuntimeError("generator didn't stop after throw()")
Guido van Rossumb940e112007-01-10 16:19:56 +000079 except StopIteration as exc:
Yury Selivanov8170e8c2015-05-09 11:44:30 -040080 # Suppress StopIteration *unless* it's the same exception that
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000081 # was passed to throw(). This prevents a StopIteration
Yury Selivanov8170e8c2015-05-09 11:44:30 -040082 # raised inside the "with" statement from being suppressed.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000083 return exc is not value
Yury Selivanov8170e8c2015-05-09 11:44:30 -040084 except RuntimeError as exc:
Gregory P. Smithba2ecd62016-06-14 09:19:20 -070085 # Don't re-raise the passed in exception. (issue27112)
86 if exc is value:
87 return False
Yury Selivanov8170e8c2015-05-09 11:44:30 -040088 # Likewise, avoid suppressing if a StopIteration exception
89 # was passed to throw() and later wrapped into a RuntimeError
90 # (see PEP 479).
91 if exc.__cause__ is value:
92 return False
93 raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000094 except:
95 # only re-raise if it's *not* the exception that was
96 # passed to throw(), because __exit__() must not raise
97 # an exception unless __exit__() itself failed. But throw()
98 # has to raise the exception to signal propagation, so this
99 # fixes the impedance mismatch between the throw() protocol
100 # and the __exit__() protocol.
101 #
102 if sys.exc_info()[1] is not value:
103 raise
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000104
105
106def contextmanager(func):
107 """@contextmanager decorator.
108
109 Typical usage:
110
111 @contextmanager
112 def some_generator(<arguments>):
113 <setup>
114 try:
115 yield <value>
116 finally:
117 <cleanup>
118
119 This makes this:
120
121 with some_generator(<arguments>) as <variable>:
122 <body>
123
124 equivalent to this:
125
126 <setup>
127 try:
128 <variable> = <value>
129 <body>
130 finally:
131 <cleanup>
132
133 """
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000134 @wraps(func)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000135 def helper(*args, **kwds):
Serhiy Storchaka101ff352015-06-28 17:06:07 +0300136 return _GeneratorContextManager(func, args, kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000137 return helper
138
139
Thomas Wouters477c8d52006-05-27 19:21:47 +0000140class closing(object):
141 """Context to automatically close something at the end of a block.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000142
143 Code like this:
144
145 with closing(<module>.open(<arguments>)) as f:
146 <block>
147
148 is equivalent to this:
149
150 f = <module>.open(<arguments>)
151 try:
152 <block>
153 finally:
154 f.close()
155
156 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000157 def __init__(self, thing):
158 self.thing = thing
159 def __enter__(self):
160 return self.thing
161 def __exit__(self, *exc_info):
162 self.thing.close()
Nick Coghlan3267a302012-05-21 22:54:43 +1000163
Berker Peksagbb44fe02014-11-28 23:28:06 +0200164
165class _RedirectStream:
166
167 _stream = None
168
169 def __init__(self, new_target):
170 self._new_target = new_target
171 # We use a list of old targets to make this CM re-entrant
172 self._old_targets = []
173
174 def __enter__(self):
175 self._old_targets.append(getattr(sys, self._stream))
176 setattr(sys, self._stream, self._new_target)
177 return self._new_target
178
179 def __exit__(self, exctype, excinst, exctb):
180 setattr(sys, self._stream, self._old_targets.pop())
181
182
183class redirect_stdout(_RedirectStream):
184 """Context manager for temporarily redirecting stdout to another file.
Nick Coghlan059def52013-10-26 18:08:15 +1000185
186 # How to send help() to stderr
187 with redirect_stdout(sys.stderr):
188 help(dir)
189
190 # How to write help() to a file
191 with open('help.txt', 'w') as f:
192 with redirect_stdout(f):
193 help(pow)
194 """
Nick Coghlan8608d262013-10-20 00:30:51 +1000195
Berker Peksagbb44fe02014-11-28 23:28:06 +0200196 _stream = "stdout"
Nick Coghlan8608d262013-10-20 00:30:51 +1000197
Nick Coghlan8608d262013-10-20 00:30:51 +1000198
Berker Peksagbb44fe02014-11-28 23:28:06 +0200199class redirect_stderr(_RedirectStream):
200 """Context manager for temporarily redirecting stderr to another file."""
201
202 _stream = "stderr"
Raymond Hettinger088cbf22013-10-10 00:46:57 -0700203
Nick Coghlan8608d262013-10-20 00:30:51 +1000204
Nick Coghlan059def52013-10-26 18:08:15 +1000205class suppress:
Nick Coghlan240f86d2013-10-17 23:40:57 +1000206 """Context manager to suppress specified exceptions
Raymond Hettingere318a882013-03-10 22:26:51 -0700207
Nick Coghlan8608d262013-10-20 00:30:51 +1000208 After the exception is suppressed, execution proceeds with the next
209 statement following the with statement.
Raymond Hettingere318a882013-03-10 22:26:51 -0700210
Nick Coghlan8608d262013-10-20 00:30:51 +1000211 with suppress(FileNotFoundError):
212 os.remove(somefile)
213 # Execution still resumes here if the file was already removed
Raymond Hettingere318a882013-03-10 22:26:51 -0700214 """
Nick Coghlan059def52013-10-26 18:08:15 +1000215
216 def __init__(self, *exceptions):
217 self._exceptions = exceptions
218
219 def __enter__(self):
220 pass
221
222 def __exit__(self, exctype, excinst, exctb):
223 # Unlike isinstance and issubclass, CPython exception handling
224 # currently only looks at the concrete type hierarchy (ignoring
225 # the instance and subclass checking hooks). While Guido considers
226 # that a bug rather than a feature, it's a fairly hard one to fix
227 # due to various internal implementation details. suppress provides
228 # the simpler issubclass based semantics, rather than trying to
229 # exactly reproduce the limitations of the CPython interpreter.
230 #
231 # See http://bugs.python.org/issue12029 for more details
232 return exctype is not None and issubclass(exctype, self._exceptions)
233
Nick Coghlan3267a302012-05-21 22:54:43 +1000234
235# Inspired by discussions on http://bugs.python.org/issue13585
236class ExitStack(object):
237 """Context manager for dynamic management of a stack of exit callbacks
238
239 For example:
240
241 with ExitStack() as stack:
242 files = [stack.enter_context(open(fname)) for fname in filenames]
243 # All opened files will automatically be closed at the end of
244 # the with statement, even if attempts to open files later
Andrew Svetlov5b898402012-12-18 21:26:36 +0200245 # in the list raise an exception
Nick Coghlan3267a302012-05-21 22:54:43 +1000246
247 """
248 def __init__(self):
249 self._exit_callbacks = deque()
250
251 def pop_all(self):
252 """Preserve the context stack by transferring it to a new instance"""
253 new_stack = type(self)()
254 new_stack._exit_callbacks = self._exit_callbacks
255 self._exit_callbacks = deque()
256 return new_stack
257
258 def _push_cm_exit(self, cm, cm_exit):
259 """Helper to correctly register callbacks to __exit__ methods"""
260 def _exit_wrapper(*exc_details):
261 return cm_exit(cm, *exc_details)
262 _exit_wrapper.__self__ = cm
263 self.push(_exit_wrapper)
264
265 def push(self, exit):
266 """Registers a callback with the standard __exit__ method signature
267
268 Can suppress exceptions the same way __exit__ methods can.
269
270 Also accepts any object with an __exit__ method (registering a call
271 to the method instead of the object itself)
272 """
273 # We use an unbound method rather than a bound method to follow
274 # the standard lookup behaviour for special methods
275 _cb_type = type(exit)
276 try:
277 exit_method = _cb_type.__exit__
278 except AttributeError:
279 # Not a context manager, so assume its a callable
280 self._exit_callbacks.append(exit)
281 else:
282 self._push_cm_exit(exit, exit_method)
283 return exit # Allow use as a decorator
284
285 def callback(self, callback, *args, **kwds):
286 """Registers an arbitrary callback and arguments.
287
288 Cannot suppress exceptions.
289 """
290 def _exit_wrapper(exc_type, exc, tb):
291 callback(*args, **kwds)
292 # We changed the signature, so using @wraps is not appropriate, but
293 # setting __wrapped__ may still help with introspection
294 _exit_wrapper.__wrapped__ = callback
295 self.push(_exit_wrapper)
296 return callback # Allow use as a decorator
297
298 def enter_context(self, cm):
299 """Enters the supplied context manager
300
301 If successful, also pushes its __exit__ method as a callback and
302 returns the result of the __enter__ method.
303 """
304 # We look up the special methods on the type to match the with statement
305 _cm_type = type(cm)
306 _exit = _cm_type.__exit__
307 result = _cm_type.__enter__(cm)
308 self._push_cm_exit(cm, _exit)
309 return result
310
311 def close(self):
312 """Immediately unwind the context stack"""
313 self.__exit__(None, None, None)
314
315 def __enter__(self):
316 return self
317
318 def __exit__(self, *exc_details):
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000319 received_exc = exc_details[0] is not None
320
Nick Coghlan77452fc2012-06-01 22:48:32 +1000321 # We manipulate the exception state so it behaves as though
322 # we were actually nesting multiple with statements
323 frame_exc = sys.exc_info()[1]
324 def _fix_exception_context(new_exc, old_exc):
Nick Coghlanadd94c92014-01-24 23:05:45 +1000325 # Context may not be correct, so find the end of the chain
Nick Coghlan77452fc2012-06-01 22:48:32 +1000326 while 1:
327 exc_context = new_exc.__context__
Nick Coghlan09761e72014-01-22 22:24:46 +1000328 if exc_context is old_exc:
329 # Context is already set correctly (see issue 20317)
330 return
331 if exc_context is None or exc_context is frame_exc:
Nick Coghlan77452fc2012-06-01 22:48:32 +1000332 break
333 new_exc = exc_context
Nick Coghlan09761e72014-01-22 22:24:46 +1000334 # Change the end of the chain to point to the exception
335 # we expect it to reference
Nick Coghlan77452fc2012-06-01 22:48:32 +1000336 new_exc.__context__ = old_exc
337
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000338 # Callbacks are invoked in LIFO order to match the behaviour of
339 # nested context managers
340 suppressed_exc = False
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000341 pending_raise = False
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000342 while self._exit_callbacks:
343 cb = self._exit_callbacks.pop()
Nick Coghlan3267a302012-05-21 22:54:43 +1000344 try:
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000345 if cb(*exc_details):
346 suppressed_exc = True
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000347 pending_raise = False
Nick Coghlan3267a302012-05-21 22:54:43 +1000348 exc_details = (None, None, None)
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000349 except:
350 new_exc_details = sys.exc_info()
Nick Coghlan77452fc2012-06-01 22:48:32 +1000351 # simulate the stack of exceptions by setting the context
352 _fix_exception_context(new_exc_details[1], exc_details[1])
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000353 pending_raise = True
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000354 exc_details = new_exc_details
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000355 if pending_raise:
356 try:
357 # bare "raise exc_details[1]" replaces our carefully
358 # set-up context
359 fixed_ctx = exc_details[1].__context__
360 raise exc_details[1]
361 except BaseException:
362 exc_details[1].__context__ = fixed_ctx
363 raise
364 return received_exc and suppressed_exc