ยปCore Development>Code coverage>Lib/contextlib.py

Python code coverage for Lib/contextlib.py

#countcontent
1n/a"""Utilities for with-statement contexts. See PEP 343."""
2n/aimport abc
3n/aimport sys
4n/afrom collections import deque
5n/afrom functools import wraps
6n/a
7n/a__all__ = ["contextmanager", "closing", "AbstractContextManager",
8n/a "ContextDecorator", "ExitStack", "redirect_stdout",
9n/a "redirect_stderr", "suppress"]
10n/a
11n/a
12n/aclass AbstractContextManager(abc.ABC):
13n/a
14n/a """An abstract base class for context managers."""
15n/a
16n/a def __enter__(self):
17n/a """Return `self` upon entering the runtime context."""
18n/a return self
19n/a
20n/a @abc.abstractmethod
21n/a def __exit__(self, exc_type, exc_value, traceback):
22n/a """Raise any exception triggered within the runtime context."""
23n/a return None
24n/a
25n/a @classmethod
26n/a def __subclasshook__(cls, C):
27n/a if cls is AbstractContextManager:
28n/a if (any("__enter__" in B.__dict__ for B in C.__mro__) and
29n/a any("__exit__" in B.__dict__ for B in C.__mro__)):
30n/a return True
31n/a return NotImplemented
32n/a
33n/a
34n/aclass ContextDecorator(object):
35n/a "A base class or mixin that enables context managers to work as decorators."
36n/a
37n/a def _recreate_cm(self):
38n/a """Return a recreated instance of self.
39n/a
40n/a Allows an otherwise one-shot context manager like
41n/a _GeneratorContextManager to support use as
42n/a a decorator via implicit recreation.
43n/a
44n/a This is a private interface just for _GeneratorContextManager.
45n/a See issue #11647 for details.
46n/a """
47n/a return self
48n/a
49n/a def __call__(self, func):
50n/a @wraps(func)
51n/a def inner(*args, **kwds):
52n/a with self._recreate_cm():
53n/a return func(*args, **kwds)
54n/a return inner
55n/a
56n/a
57n/aclass _GeneratorContextManager(ContextDecorator, AbstractContextManager):
58n/a """Helper for @contextmanager decorator."""
59n/a
60n/a def __init__(self, func, args, kwds):
61n/a self.gen = func(*args, **kwds)
62n/a self.func, self.args, self.kwds = func, args, kwds
63n/a # Issue 19330: ensure context manager instances have good docstrings
64n/a doc = getattr(func, "__doc__", None)
65n/a if doc is None:
66n/a doc = type(self).__doc__
67n/a self.__doc__ = doc
68n/a # Unfortunately, this still doesn't provide good help output when
69n/a # inspecting the created context manager instances, since pydoc
70n/a # currently bypasses the instance docstring and shows the docstring
71n/a # for the class instead.
72n/a # See http://bugs.python.org/issue19404 for more details.
73n/a
74n/a def _recreate_cm(self):
75n/a # _GCM instances are one-shot context managers, so the
76n/a # CM must be recreated each time a decorated function is
77n/a # called
78n/a return self.__class__(self.func, self.args, self.kwds)
79n/a
80n/a def __enter__(self):
81n/a try:
82n/a return next(self.gen)
83n/a except StopIteration:
84n/a raise RuntimeError("generator didn't yield") from None
85n/a
86n/a def __exit__(self, type, value, traceback):
87n/a if type is None:
88n/a try:
89n/a next(self.gen)
90n/a except StopIteration:
91n/a return
92n/a else:
93n/a raise RuntimeError("generator didn't stop")
94n/a else:
95n/a if value is None:
96n/a # Need to force instantiation so we can reliably
97n/a # tell if we get the same exception back
98n/a value = type()
99n/a try:
100n/a self.gen.throw(type, value, traceback)
101n/a raise RuntimeError("generator didn't stop after throw()")
102n/a except StopIteration as exc:
103n/a # Suppress StopIteration *unless* it's the same exception that
104n/a # was passed to throw(). This prevents a StopIteration
105n/a # raised inside the "with" statement from being suppressed.
106n/a return exc is not value
107n/a except RuntimeError as exc:
108n/a # Don't re-raise the passed in exception. (issue27112)
109n/a if exc is value:
110n/a return False
111n/a # Likewise, avoid suppressing if a StopIteration exception
112n/a # was passed to throw() and later wrapped into a RuntimeError
113n/a # (see PEP 479).
114n/a if exc.__cause__ is value:
115n/a return False
116n/a raise
117n/a except:
118n/a # only re-raise if it's *not* the exception that was
119n/a # passed to throw(), because __exit__() must not raise
120n/a # an exception unless __exit__() itself failed. But throw()
121n/a # has to raise the exception to signal propagation, so this
122n/a # fixes the impedance mismatch between the throw() protocol
123n/a # and the __exit__() protocol.
124n/a #
125n/a if sys.exc_info()[1] is not value:
126n/a raise
127n/a
128n/a
129n/adef contextmanager(func):
130n/a """@contextmanager decorator.
131n/a
132n/a Typical usage:
133n/a
134n/a @contextmanager
135n/a def some_generator(<arguments>):
136n/a <setup>
137n/a try:
138n/a yield <value>
139n/a finally:
140n/a <cleanup>
141n/a
142n/a This makes this:
143n/a
144n/a with some_generator(<arguments>) as <variable>:
145n/a <body>
146n/a
147n/a equivalent to this:
148n/a
149n/a <setup>
150n/a try:
151n/a <variable> = <value>
152n/a <body>
153n/a finally:
154n/a <cleanup>
155n/a
156n/a """
157n/a @wraps(func)
158n/a def helper(*args, **kwds):
159n/a return _GeneratorContextManager(func, args, kwds)
160n/a return helper
161n/a
162n/a
163n/aclass closing(AbstractContextManager):
164n/a """Context to automatically close something at the end of a block.
165n/a
166n/a Code like this:
167n/a
168n/a with closing(<module>.open(<arguments>)) as f:
169n/a <block>
170n/a
171n/a is equivalent to this:
172n/a
173n/a f = <module>.open(<arguments>)
174n/a try:
175n/a <block>
176n/a finally:
177n/a f.close()
178n/a
179n/a """
180n/a def __init__(self, thing):
181n/a self.thing = thing
182n/a def __enter__(self):
183n/a return self.thing
184n/a def __exit__(self, *exc_info):
185n/a self.thing.close()
186n/a
187n/a
188n/aclass _RedirectStream(AbstractContextManager):
189n/a
190n/a _stream = None
191n/a
192n/a def __init__(self, new_target):
193n/a self._new_target = new_target
194n/a # We use a list of old targets to make this CM re-entrant
195n/a self._old_targets = []
196n/a
197n/a def __enter__(self):
198n/a self._old_targets.append(getattr(sys, self._stream))
199n/a setattr(sys, self._stream, self._new_target)
200n/a return self._new_target
201n/a
202n/a def __exit__(self, exctype, excinst, exctb):
203n/a setattr(sys, self._stream, self._old_targets.pop())
204n/a
205n/a
206n/aclass redirect_stdout(_RedirectStream):
207n/a """Context manager for temporarily redirecting stdout to another file.
208n/a
209n/a # How to send help() to stderr
210n/a with redirect_stdout(sys.stderr):
211n/a help(dir)
212n/a
213n/a # How to write help() to a file
214n/a with open('help.txt', 'w') as f:
215n/a with redirect_stdout(f):
216n/a help(pow)
217n/a """
218n/a
219n/a _stream = "stdout"
220n/a
221n/a
222n/aclass redirect_stderr(_RedirectStream):
223n/a """Context manager for temporarily redirecting stderr to another file."""
224n/a
225n/a _stream = "stderr"
226n/a
227n/a
228n/aclass suppress(AbstractContextManager):
229n/a """Context manager to suppress specified exceptions
230n/a
231n/a After the exception is suppressed, execution proceeds with the next
232n/a statement following the with statement.
233n/a
234n/a with suppress(FileNotFoundError):
235n/a os.remove(somefile)
236n/a # Execution still resumes here if the file was already removed
237n/a """
238n/a
239n/a def __init__(self, *exceptions):
240n/a self._exceptions = exceptions
241n/a
242n/a def __enter__(self):
243n/a pass
244n/a
245n/a def __exit__(self, exctype, excinst, exctb):
246n/a # Unlike isinstance and issubclass, CPython exception handling
247n/a # currently only looks at the concrete type hierarchy (ignoring
248n/a # the instance and subclass checking hooks). While Guido considers
249n/a # that a bug rather than a feature, it's a fairly hard one to fix
250n/a # due to various internal implementation details. suppress provides
251n/a # the simpler issubclass based semantics, rather than trying to
252n/a # exactly reproduce the limitations of the CPython interpreter.
253n/a #
254n/a # See http://bugs.python.org/issue12029 for more details
255n/a return exctype is not None and issubclass(exctype, self._exceptions)
256n/a
257n/a
258n/a# Inspired by discussions on http://bugs.python.org/issue13585
259n/aclass ExitStack(AbstractContextManager):
260n/a """Context manager for dynamic management of a stack of exit callbacks
261n/a
262n/a For example:
263n/a
264n/a with ExitStack() as stack:
265n/a files = [stack.enter_context(open(fname)) for fname in filenames]
266n/a # All opened files will automatically be closed at the end of
267n/a # the with statement, even if attempts to open files later
268n/a # in the list raise an exception
269n/a
270n/a """
271n/a def __init__(self):
272n/a self._exit_callbacks = deque()
273n/a
274n/a def pop_all(self):
275n/a """Preserve the context stack by transferring it to a new instance"""
276n/a new_stack = type(self)()
277n/a new_stack._exit_callbacks = self._exit_callbacks
278n/a self._exit_callbacks = deque()
279n/a return new_stack
280n/a
281n/a def _push_cm_exit(self, cm, cm_exit):
282n/a """Helper to correctly register callbacks to __exit__ methods"""
283n/a def _exit_wrapper(*exc_details):
284n/a return cm_exit(cm, *exc_details)
285n/a _exit_wrapper.__self__ = cm
286n/a self.push(_exit_wrapper)
287n/a
288n/a def push(self, exit):
289n/a """Registers a callback with the standard __exit__ method signature
290n/a
291n/a Can suppress exceptions the same way __exit__ methods can.
292n/a
293n/a Also accepts any object with an __exit__ method (registering a call
294n/a to the method instead of the object itself)
295n/a """
296n/a # We use an unbound method rather than a bound method to follow
297n/a # the standard lookup behaviour for special methods
298n/a _cb_type = type(exit)
299n/a try:
300n/a exit_method = _cb_type.__exit__
301n/a except AttributeError:
302n/a # Not a context manager, so assume its a callable
303n/a self._exit_callbacks.append(exit)
304n/a else:
305n/a self._push_cm_exit(exit, exit_method)
306n/a return exit # Allow use as a decorator
307n/a
308n/a def callback(self, callback, *args, **kwds):
309n/a """Registers an arbitrary callback and arguments.
310n/a
311n/a Cannot suppress exceptions.
312n/a """
313n/a def _exit_wrapper(exc_type, exc, tb):
314n/a callback(*args, **kwds)
315n/a # We changed the signature, so using @wraps is not appropriate, but
316n/a # setting __wrapped__ may still help with introspection
317n/a _exit_wrapper.__wrapped__ = callback
318n/a self.push(_exit_wrapper)
319n/a return callback # Allow use as a decorator
320n/a
321n/a def enter_context(self, cm):
322n/a """Enters the supplied context manager
323n/a
324n/a If successful, also pushes its __exit__ method as a callback and
325n/a returns the result of the __enter__ method.
326n/a """
327n/a # We look up the special methods on the type to match the with statement
328n/a _cm_type = type(cm)
329n/a _exit = _cm_type.__exit__
330n/a result = _cm_type.__enter__(cm)
331n/a self._push_cm_exit(cm, _exit)
332n/a return result
333n/a
334n/a def close(self):
335n/a """Immediately unwind the context stack"""
336n/a self.__exit__(None, None, None)
337n/a
338n/a def __exit__(self, *exc_details):
339n/a received_exc = exc_details[0] is not None
340n/a
341n/a # We manipulate the exception state so it behaves as though
342n/a # we were actually nesting multiple with statements
343n/a frame_exc = sys.exc_info()[1]
344n/a def _fix_exception_context(new_exc, old_exc):
345n/a # Context may not be correct, so find the end of the chain
346n/a while 1:
347n/a exc_context = new_exc.__context__
348n/a if exc_context is old_exc:
349n/a # Context is already set correctly (see issue 20317)
350n/a return
351n/a if exc_context is None or exc_context is frame_exc:
352n/a break
353n/a new_exc = exc_context
354n/a # Change the end of the chain to point to the exception
355n/a # we expect it to reference
356n/a new_exc.__context__ = old_exc
357n/a
358n/a # Callbacks are invoked in LIFO order to match the behaviour of
359n/a # nested context managers
360n/a suppressed_exc = False
361n/a pending_raise = False
362n/a while self._exit_callbacks:
363n/a cb = self._exit_callbacks.pop()
364n/a try:
365n/a if cb(*exc_details):
366n/a suppressed_exc = True
367n/a pending_raise = False
368n/a exc_details = (None, None, None)
369n/a except:
370n/a new_exc_details = sys.exc_info()
371n/a # simulate the stack of exceptions by setting the context
372n/a _fix_exception_context(new_exc_details[1], exc_details[1])
373n/a pending_raise = True
374n/a exc_details = new_exc_details
375n/a if pending_raise:
376n/a try:
377n/a # bare "raise exc_details[1]" replaces our carefully
378n/a # set-up context
379n/a fixed_ctx = exc_details[1].__context__
380n/a raise exc_details[1]
381n/a except BaseException:
382n/a exc_details[1].__context__ = fixed_ctx
383n/a raise
384n/a return received_exc and suppressed_exc