blob: 82ee955a8b2d54b0448a52626d96cbc30f20067f [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",
Nick Coghlan240f86d2013-10-17 23:40:57 +10008 "redirect_stdout", "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
Nick Coghlan0ded3e32011-05-05 23:49:25 +100037 def __init__(self, func, *args, **kwds):
38 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
55 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:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000080 # Suppress the exception *unless* it's the same exception that
81 # was passed to throw(). This prevents a StopIteration
82 # raised inside the "with" statement from being suppressed
83 return exc is not value
84 except:
85 # only re-raise if it's *not* the exception that was
86 # passed to throw(), because __exit__() must not raise
87 # an exception unless __exit__() itself failed. But throw()
88 # has to raise the exception to signal propagation, so this
89 # fixes the impedance mismatch between the throw() protocol
90 # and the __exit__() protocol.
91 #
92 if sys.exc_info()[1] is not value:
93 raise
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000094
95
96def contextmanager(func):
97 """@contextmanager decorator.
98
99 Typical usage:
100
101 @contextmanager
102 def some_generator(<arguments>):
103 <setup>
104 try:
105 yield <value>
106 finally:
107 <cleanup>
108
109 This makes this:
110
111 with some_generator(<arguments>) as <variable>:
112 <body>
113
114 equivalent to this:
115
116 <setup>
117 try:
118 <variable> = <value>
119 <body>
120 finally:
121 <cleanup>
122
123 """
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000124 @wraps(func)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000125 def helper(*args, **kwds):
Nick Coghlan0ded3e32011-05-05 23:49:25 +1000126 return _GeneratorContextManager(func, *args, **kwds)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000127 return helper
128
129
Thomas Wouters477c8d52006-05-27 19:21:47 +0000130class closing(object):
131 """Context to automatically close something at the end of a block.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000132
133 Code like this:
134
135 with closing(<module>.open(<arguments>)) as f:
136 <block>
137
138 is equivalent to this:
139
140 f = <module>.open(<arguments>)
141 try:
142 <block>
143 finally:
144 f.close()
145
146 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000147 def __init__(self, thing):
148 self.thing = thing
149 def __enter__(self):
150 return self.thing
151 def __exit__(self, *exc_info):
152 self.thing.close()
Nick Coghlan3267a302012-05-21 22:54:43 +1000153
Nick Coghlan059def52013-10-26 18:08:15 +1000154class redirect_stdout:
155 """Context manager for temporarily redirecting stdout to another file
156
157 # How to send help() to stderr
158 with redirect_stdout(sys.stderr):
159 help(dir)
160
161 # How to write help() to a file
162 with open('help.txt', 'w') as f:
163 with redirect_stdout(f):
164 help(pow)
165 """
Nick Coghlan8608d262013-10-20 00:30:51 +1000166
167 def __init__(self, new_target):
168 self._new_target = new_target
Nick Coghlan8e113b42013-11-03 17:00:51 +1000169 # We use a list of old targets to make this CM re-entrant
170 self._old_targets = []
Nick Coghlan8608d262013-10-20 00:30:51 +1000171
172 def __enter__(self):
Nick Coghlan8e113b42013-11-03 17:00:51 +1000173 self._old_targets.append(sys.stdout)
Nick Coghlan8608d262013-10-20 00:30:51 +1000174 sys.stdout = self._new_target
175 return self._new_target
176
177 def __exit__(self, exctype, excinst, exctb):
Nick Coghlan8e113b42013-11-03 17:00:51 +1000178 sys.stdout = self._old_targets.pop()
Raymond Hettinger088cbf22013-10-10 00:46:57 -0700179
Nick Coghlan8608d262013-10-20 00:30:51 +1000180
Nick Coghlan059def52013-10-26 18:08:15 +1000181class suppress:
Nick Coghlan240f86d2013-10-17 23:40:57 +1000182 """Context manager to suppress specified exceptions
Raymond Hettingere318a882013-03-10 22:26:51 -0700183
Nick Coghlan8608d262013-10-20 00:30:51 +1000184 After the exception is suppressed, execution proceeds with the next
185 statement following the with statement.
Raymond Hettingere318a882013-03-10 22:26:51 -0700186
Nick Coghlan8608d262013-10-20 00:30:51 +1000187 with suppress(FileNotFoundError):
188 os.remove(somefile)
189 # Execution still resumes here if the file was already removed
Raymond Hettingere318a882013-03-10 22:26:51 -0700190 """
Nick Coghlan059def52013-10-26 18:08:15 +1000191
192 def __init__(self, *exceptions):
193 self._exceptions = exceptions
194
195 def __enter__(self):
196 pass
197
198 def __exit__(self, exctype, excinst, exctb):
199 # Unlike isinstance and issubclass, CPython exception handling
200 # currently only looks at the concrete type hierarchy (ignoring
201 # the instance and subclass checking hooks). While Guido considers
202 # that a bug rather than a feature, it's a fairly hard one to fix
203 # due to various internal implementation details. suppress provides
204 # the simpler issubclass based semantics, rather than trying to
205 # exactly reproduce the limitations of the CPython interpreter.
206 #
207 # See http://bugs.python.org/issue12029 for more details
208 return exctype is not None and issubclass(exctype, self._exceptions)
209
Nick Coghlan3267a302012-05-21 22:54:43 +1000210
211# Inspired by discussions on http://bugs.python.org/issue13585
212class ExitStack(object):
213 """Context manager for dynamic management of a stack of exit callbacks
214
215 For example:
216
217 with ExitStack() as stack:
218 files = [stack.enter_context(open(fname)) for fname in filenames]
219 # All opened files will automatically be closed at the end of
220 # the with statement, even if attempts to open files later
Andrew Svetlov5b898402012-12-18 21:26:36 +0200221 # in the list raise an exception
Nick Coghlan3267a302012-05-21 22:54:43 +1000222
223 """
224 def __init__(self):
225 self._exit_callbacks = deque()
226
227 def pop_all(self):
228 """Preserve the context stack by transferring it to a new instance"""
229 new_stack = type(self)()
230 new_stack._exit_callbacks = self._exit_callbacks
231 self._exit_callbacks = deque()
232 return new_stack
233
234 def _push_cm_exit(self, cm, cm_exit):
235 """Helper to correctly register callbacks to __exit__ methods"""
236 def _exit_wrapper(*exc_details):
237 return cm_exit(cm, *exc_details)
238 _exit_wrapper.__self__ = cm
239 self.push(_exit_wrapper)
240
241 def push(self, exit):
242 """Registers a callback with the standard __exit__ method signature
243
244 Can suppress exceptions the same way __exit__ methods can.
245
246 Also accepts any object with an __exit__ method (registering a call
247 to the method instead of the object itself)
248 """
249 # We use an unbound method rather than a bound method to follow
250 # the standard lookup behaviour for special methods
251 _cb_type = type(exit)
252 try:
253 exit_method = _cb_type.__exit__
254 except AttributeError:
255 # Not a context manager, so assume its a callable
256 self._exit_callbacks.append(exit)
257 else:
258 self._push_cm_exit(exit, exit_method)
259 return exit # Allow use as a decorator
260
261 def callback(self, callback, *args, **kwds):
262 """Registers an arbitrary callback and arguments.
263
264 Cannot suppress exceptions.
265 """
266 def _exit_wrapper(exc_type, exc, tb):
267 callback(*args, **kwds)
268 # We changed the signature, so using @wraps is not appropriate, but
269 # setting __wrapped__ may still help with introspection
270 _exit_wrapper.__wrapped__ = callback
271 self.push(_exit_wrapper)
272 return callback # Allow use as a decorator
273
274 def enter_context(self, cm):
275 """Enters the supplied context manager
276
277 If successful, also pushes its __exit__ method as a callback and
278 returns the result of the __enter__ method.
279 """
280 # We look up the special methods on the type to match the with statement
281 _cm_type = type(cm)
282 _exit = _cm_type.__exit__
283 result = _cm_type.__enter__(cm)
284 self._push_cm_exit(cm, _exit)
285 return result
286
287 def close(self):
288 """Immediately unwind the context stack"""
289 self.__exit__(None, None, None)
290
291 def __enter__(self):
292 return self
293
294 def __exit__(self, *exc_details):
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000295 received_exc = exc_details[0] is not None
296
Nick Coghlan77452fc2012-06-01 22:48:32 +1000297 # We manipulate the exception state so it behaves as though
298 # we were actually nesting multiple with statements
299 frame_exc = sys.exc_info()[1]
300 def _fix_exception_context(new_exc, old_exc):
Nick Coghlanadd94c92014-01-24 23:05:45 +1000301 # Context may not be correct, so find the end of the chain
Nick Coghlan77452fc2012-06-01 22:48:32 +1000302 while 1:
303 exc_context = new_exc.__context__
Nick Coghlan09761e72014-01-22 22:24:46 +1000304 if exc_context is old_exc:
305 # Context is already set correctly (see issue 20317)
306 return
307 if exc_context is None or exc_context is frame_exc:
Nick Coghlan77452fc2012-06-01 22:48:32 +1000308 break
309 new_exc = exc_context
Nick Coghlan09761e72014-01-22 22:24:46 +1000310 # Change the end of the chain to point to the exception
311 # we expect it to reference
Nick Coghlan77452fc2012-06-01 22:48:32 +1000312 new_exc.__context__ = old_exc
313
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000314 # Callbacks are invoked in LIFO order to match the behaviour of
315 # nested context managers
316 suppressed_exc = False
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000317 pending_raise = False
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000318 while self._exit_callbacks:
319 cb = self._exit_callbacks.pop()
Nick Coghlan3267a302012-05-21 22:54:43 +1000320 try:
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000321 if cb(*exc_details):
322 suppressed_exc = True
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000323 pending_raise = False
Nick Coghlan3267a302012-05-21 22:54:43 +1000324 exc_details = (None, None, None)
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000325 except:
326 new_exc_details = sys.exc_info()
Nick Coghlan77452fc2012-06-01 22:48:32 +1000327 # simulate the stack of exceptions by setting the context
328 _fix_exception_context(new_exc_details[1], exc_details[1])
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000329 pending_raise = True
Nick Coghlana5bd2a12012-06-01 00:00:38 +1000330 exc_details = new_exc_details
Nick Coghlan1a33b2f2013-10-01 23:24:56 +1000331 if pending_raise:
332 try:
333 # bare "raise exc_details[1]" replaces our carefully
334 # set-up context
335 fixed_ctx = exc_details[1].__context__
336 raise exc_details[1]
337 except BaseException:
338 exc_details[1].__context__ = fixed_ctx
339 raise
340 return received_exc and suppressed_exc