blob: 5377987ddfe13dcbbbf7ded66acf59756aeaf1ff [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:
85 # Likewise, avoid suppressing if a StopIteration exception
86 # was passed to throw() and later wrapped into a RuntimeError
87 # (see PEP 479).
88 if exc.__cause__ is value:
89 return False
90 raise
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000091 except:
92 # only re-raise if it's *not* the exception that was
93 # passed to throw(), because __exit__() must not raise
94 # an exception unless __exit__() itself failed. But throw()
95 # has to raise the exception to signal propagation, so this
96 # fixes the impedance mismatch between the throw() protocol
97 # and the __exit__() protocol.
98 #
99 if sys.exc_info()[1] is not value:
100 raise
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000101
102
103def contextmanager(func):
104 """@contextmanager decorator.
105
106 Typical usage:
107
108 @contextmanager
109 def some_generator(<arguments>):
110 <setup>
111 try:
112 yield <value>
113 finally:
114 <cleanup>
115
116 This makes this:
117
118 with some_generator(<arguments>) as <variable>:
119 <body>
120
121 equivalent to this:
122
123 <setup>
124 try:
125 <variable> = <value>
126 <body>
127 finally:
128 <cleanup>
129
130 """
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000131 @wraps(func)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000132 def helper(*args, **kwds):
Serhiy Storchaka101ff352015-06-28 17:06:07 +0300133 return _GeneratorContextManager(func, args, kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000134 return helper
135
136
Thomas Wouters477c8d52006-05-27 19:21:47 +0000137class closing(object):
138 """Context to automatically close something at the end of a block.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000139
140 Code like this:
141
142 with closing(<module>.open(<arguments>)) as f:
143 <block>
144
145 is equivalent to this:
146
147 f = <module>.open(<arguments>)
148 try:
149 <block>
150 finally:
151 f.close()
152
153 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000154 def __init__(self, thing):
155 self.thing = thing
156 def __enter__(self):
157 return self.thing
158 def __exit__(self, *exc_info):
159 self.thing.close()
Nick Coghlan3267a302012-05-21 22:54:43 +1000160
Berker Peksagbb44fe02014-11-28 23:28:06 +0200161
162class _RedirectStream:
163
164 _stream = None
165
166 def __init__(self, new_target):
167 self._new_target = new_target
168 # We use a list of old targets to make this CM re-entrant
169 self._old_targets = []
170
171 def __enter__(self):
172 self._old_targets.append(getattr(sys, self._stream))
173 setattr(sys, self._stream, self._new_target)
174 return self._new_target
175
176 def __exit__(self, exctype, excinst, exctb):
177 setattr(sys, self._stream, self._old_targets.pop())
178
179
180class redirect_stdout(_RedirectStream):
181 """Context manager for temporarily redirecting stdout to another file.
Nick Coghlan059def52013-10-26 18:08:15 +1000182
183 # How to send help() to stderr
184 with redirect_stdout(sys.stderr):
185 help(dir)
186
187 # How to write help() to a file
188 with open('help.txt', 'w') as f:
189 with redirect_stdout(f):
190 help(pow)
191 """
Nick Coghlan8608d262013-10-20 00:30:51 +1000192
Berker Peksagbb44fe02014-11-28 23:28:06 +0200193 _stream = "stdout"
Nick Coghlan8608d262013-10-20 00:30:51 +1000194
Nick Coghlan8608d262013-10-20 00:30:51 +1000195
Berker Peksagbb44fe02014-11-28 23:28:06 +0200196class redirect_stderr(_RedirectStream):
197 """Context manager for temporarily redirecting stderr to another file."""
198
199 _stream = "stderr"
Raymond Hettinger088cbf22013-10-10 00:46:57 -0700200
Nick Coghlan8608d262013-10-20 00:30:51 +1000201
Nick Coghlan059def52013-10-26 18:08:15 +1000202class suppress:
Nick Coghlan240f86d2013-10-17 23:40:57 +1000203 """Context manager to suppress specified exceptions
Raymond Hettingere318a882013-03-10 22:26:51 -0700204
Nick Coghlan8608d262013-10-20 00:30:51 +1000205 After the exception is suppressed, execution proceeds with the next
206 statement following the with statement.
Raymond Hettingere318a882013-03-10 22:26:51 -0700207
Nick Coghlan8608d262013-10-20 00:30:51 +1000208 with suppress(FileNotFoundError):
209 os.remove(somefile)
210 # Execution still resumes here if the file was already removed
Raymond Hettingere318a882013-03-10 22:26:51 -0700211 """
Nick Coghlan059def52013-10-26 18:08:15 +1000212
213 def __init__(self, *exceptions):
214 self._exceptions = exceptions
215
216 def __enter__(self):
217 pass
218
219 def __exit__(self, exctype, excinst, exctb):
220 # Unlike isinstance and issubclass, CPython exception handling
221 # currently only looks at the concrete type hierarchy (ignoring
222 # the instance and subclass checking hooks). While Guido considers
223 # that a bug rather than a feature, it's a fairly hard one to fix
224 # due to various internal implementation details. suppress provides
225 # the simpler issubclass based semantics, rather than trying to
226 # exactly reproduce the limitations of the CPython interpreter.
227 #
228 # See http://bugs.python.org/issue12029 for more details
229 return exctype is not None and issubclass(exctype, self._exceptions)
230
Nick Coghlan3267a302012-05-21 22:54:43 +1000231
232# Inspired by discussions on http://bugs.python.org/issue13585
233class ExitStack(object):
234 """Context manager for dynamic management of a stack of exit callbacks
235
236 For example:
237
238 with ExitStack() as stack:
239 files = [stack.enter_context(open(fname)) for fname in filenames]
240 # All opened files will automatically be closed at the end of
241 # the with statement, even if attempts to open files later
Andrew Svetlov5b898402012-12-18 21:26:36 +0200242 # in the list raise an exception
Nick Coghlan3267a302012-05-21 22:54:43 +1000243
244 """
245 def __init__(self):
246 self._exit_callbacks = deque()
247
248 def pop_all(self):
249 """Preserve the context stack by transferring it to a new instance"""
250 new_stack = type(self)()
251 new_stack._exit_callbacks = self._exit_callbacks
252 self._exit_callbacks = deque()
253 return new_stack
254
255 def _push_cm_exit(self, cm, cm_exit):
256 """Helper to correctly register callbacks to __exit__ methods"""
257 def _exit_wrapper(*exc_details):
258 return cm_exit(cm, *exc_details)
259 _exit_wrapper.__self__ = cm
260 self.push(_exit_wrapper)
261
262 def push(self, exit):
263 """Registers a callback with the standard __exit__ method signature
264
265 Can suppress exceptions the same way __exit__ methods can.
266
267 Also accepts any object with an __exit__ method (registering a call
268 to the method instead of the object itself)
269 """
270 # We use an unbound method rather than a bound method to follow
271 # the standard lookup behaviour for special methods
272 _cb_type = type(exit)
273 try:
274 exit_method = _cb_type.__exit__
275 except AttributeError:
276 # Not a context manager, so assume its a callable
277 self._exit_callbacks.append(exit)
278 else:
279 self._push_cm_exit(exit, exit_method)
280 return exit # Allow use as a decorator
281
282 def callback(self, callback, *args, **kwds):
283 """Registers an arbitrary callback and arguments.
284
285 Cannot suppress exceptions.
286 """
287 def _exit_wrapper(exc_type, exc, tb):
288 callback(*args, **kwds)
289 # We changed the signature, so using @wraps is not appropriate, but
290 # setting __wrapped__ may still help with introspection
291 _exit_wrapper.__wrapped__ = callback
292 self.push(_exit_wrapper)
293 return callback # Allow use as a decorator
294
295 def enter_context(self, cm):
296 """Enters the supplied context manager
297
298 If successful, also pushes its __exit__ method as a callback and
299 returns the result of the __enter__ method.
300 """
301 # We look up the special methods on the type to match the with statement
302 _cm_type = type(cm)
303 _exit = _cm_type.__exit__
304 result = _cm_type.__enter__(cm)
305 self._push_cm_exit(cm, _exit)
306 return result
307
308 def close(self):
309 """Immediately unwind the context stack"""
310 self.__exit__(None, None, None)
311
312 def __enter__(self):
313 return self
314
315 def __exit__(self, *exc_details):
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000316 received_exc = exc_details[0] is not None
317
Nick Coghlan77452fc2012-06-01 22:48:32 +1000318 # We manipulate the exception state so it behaves as though
319 # we were actually nesting multiple with statements
320 frame_exc = sys.exc_info()[1]
321 def _fix_exception_context(new_exc, old_exc):
Nick Coghlanadd94c92014-01-24 23:05:45 +1000322 # Context may not be correct, so find the end of the chain
Nick Coghlan77452fc2012-06-01 22:48:32 +1000323 while 1:
324 exc_context = new_exc.__context__
Nick Coghlan09761e72014-01-22 22:24:46 +1000325 if exc_context is old_exc:
326 # Context is already set correctly (see issue 20317)
327 return
328 if exc_context is None or exc_context is frame_exc:
Nick Coghlan77452fc2012-06-01 22:48:32 +1000329 break
330 new_exc = exc_context
Nick Coghlan09761e72014-01-22 22:24:46 +1000331 # Change the end of the chain to point to the exception
332 # we expect it to reference
Nick Coghlan77452fc2012-06-01 22:48:32 +1000333 new_exc.__context__ = old_exc
334
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000335 # Callbacks are invoked in LIFO order to match the behaviour of
336 # nested context managers
337 suppressed_exc = False
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000338 pending_raise = False
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000339 while self._exit_callbacks:
340 cb = self._exit_callbacks.pop()
Nick Coghlan3267a302012-05-21 22:54:43 +1000341 try:
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000342 if cb(*exc_details):
343 suppressed_exc = True
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000344 pending_raise = False
Nick Coghlan3267a302012-05-21 22:54:43 +1000345 exc_details = (None, None, None)
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000346 except:
347 new_exc_details = sys.exc_info()
Nick Coghlan77452fc2012-06-01 22:48:32 +1000348 # simulate the stack of exceptions by setting the context
349 _fix_exception_context(new_exc_details[1], exc_details[1])
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000350 pending_raise = True
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000351 exc_details = new_exc_details
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000352 if pending_raise:
353 try:
354 # bare "raise exc_details[1]" replaces our carefully
355 # set-up context
356 fixed_ctx = exc_details[1].__context__
357 raise exc_details[1]
358 except BaseException:
359 exc_details[1].__context__ = fixed_ctx
360 raise
361 return received_exc and suppressed_exc