contextlib.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. """Utilities for with-statement contexts. See PEP 343."""
  2. import abc
  3. import sys
  4. import _collections_abc
  5. from collections import deque
  6. from functools import wraps
  7. from types import MethodType, GenericAlias
  8. __all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext",
  9. "AbstractContextManager", "AbstractAsyncContextManager",
  10. "AsyncExitStack", "ContextDecorator", "ExitStack",
  11. "redirect_stdout", "redirect_stderr", "suppress"]
  12. class AbstractContextManager(abc.ABC):
  13. """An abstract base class for context managers."""
  14. __class_getitem__ = classmethod(GenericAlias)
  15. def __enter__(self):
  16. """Return `self` upon entering the runtime context."""
  17. return self
  18. @abc.abstractmethod
  19. def __exit__(self, exc_type, exc_value, traceback):
  20. """Raise any exception triggered within the runtime context."""
  21. return None
  22. @classmethod
  23. def __subclasshook__(cls, C):
  24. if cls is AbstractContextManager:
  25. return _collections_abc._check_methods(C, "__enter__", "__exit__")
  26. return NotImplemented
  27. class AbstractAsyncContextManager(abc.ABC):
  28. """An abstract base class for asynchronous context managers."""
  29. __class_getitem__ = classmethod(GenericAlias)
  30. async def __aenter__(self):
  31. """Return `self` upon entering the runtime context."""
  32. return self
  33. @abc.abstractmethod
  34. async def __aexit__(self, exc_type, exc_value, traceback):
  35. """Raise any exception triggered within the runtime context."""
  36. return None
  37. @classmethod
  38. def __subclasshook__(cls, C):
  39. if cls is AbstractAsyncContextManager:
  40. return _collections_abc._check_methods(C, "__aenter__",
  41. "__aexit__")
  42. return NotImplemented
  43. class ContextDecorator(object):
  44. "A base class or mixin that enables context managers to work as decorators."
  45. def _recreate_cm(self):
  46. """Return a recreated instance of self.
  47. Allows an otherwise one-shot context manager like
  48. _GeneratorContextManager to support use as
  49. a decorator via implicit recreation.
  50. This is a private interface just for _GeneratorContextManager.
  51. See issue #11647 for details.
  52. """
  53. return self
  54. def __call__(self, func):
  55. @wraps(func)
  56. def inner(*args, **kwds):
  57. with self._recreate_cm():
  58. return func(*args, **kwds)
  59. return inner
  60. class _GeneratorContextManagerBase:
  61. """Shared functionality for @contextmanager and @asynccontextmanager."""
  62. def __init__(self, func, args, kwds):
  63. self.gen = func(*args, **kwds)
  64. self.func, self.args, self.kwds = func, args, kwds
  65. # Issue 19330: ensure context manager instances have good docstrings
  66. doc = getattr(func, "__doc__", None)
  67. if doc is None:
  68. doc = type(self).__doc__
  69. self.__doc__ = doc
  70. # Unfortunately, this still doesn't provide good help output when
  71. # inspecting the created context manager instances, since pydoc
  72. # currently bypasses the instance docstring and shows the docstring
  73. # for the class instead.
  74. # See http://bugs.python.org/issue19404 for more details.
  75. class _GeneratorContextManager(_GeneratorContextManagerBase,
  76. AbstractContextManager,
  77. ContextDecorator):
  78. """Helper for @contextmanager decorator."""
  79. def _recreate_cm(self):
  80. # _GCM instances are one-shot context managers, so the
  81. # CM must be recreated each time a decorated function is
  82. # called
  83. return self.__class__(self.func, self.args, self.kwds)
  84. def __enter__(self):
  85. # do not keep args and kwds alive unnecessarily
  86. # they are only needed for recreation, which is not possible anymore
  87. del self.args, self.kwds, self.func
  88. try:
  89. return next(self.gen)
  90. except StopIteration:
  91. raise RuntimeError("generator didn't yield") from None
  92. def __exit__(self, type, value, traceback):
  93. if type is None:
  94. try:
  95. next(self.gen)
  96. except StopIteration:
  97. return False
  98. else:
  99. raise RuntimeError("generator didn't stop")
  100. else:
  101. if value is None:
  102. # Need to force instantiation so we can reliably
  103. # tell if we get the same exception back
  104. value = type()
  105. try:
  106. self.gen.throw(type, value, traceback)
  107. except StopIteration as exc:
  108. # Suppress StopIteration *unless* it's the same exception that
  109. # was passed to throw(). This prevents a StopIteration
  110. # raised inside the "with" statement from being suppressed.
  111. return exc is not value
  112. except RuntimeError as exc:
  113. # Don't re-raise the passed in exception. (issue27122)
  114. if exc is value:
  115. return False
  116. # Likewise, avoid suppressing if a StopIteration exception
  117. # was passed to throw() and later wrapped into a RuntimeError
  118. # (see PEP 479).
  119. if type is StopIteration and exc.__cause__ is value:
  120. return False
  121. raise
  122. except:
  123. # only re-raise if it's *not* the exception that was
  124. # passed to throw(), because __exit__() must not raise
  125. # an exception unless __exit__() itself failed. But throw()
  126. # has to raise the exception to signal propagation, so this
  127. # fixes the impedance mismatch between the throw() protocol
  128. # and the __exit__() protocol.
  129. #
  130. # This cannot use 'except BaseException as exc' (as in the
  131. # async implementation) to maintain compatibility with
  132. # Python 2, where old-style class exceptions are not caught
  133. # by 'except BaseException'.
  134. if sys.exc_info()[1] is value:
  135. return False
  136. raise
  137. raise RuntimeError("generator didn't stop after throw()")
  138. class _AsyncGeneratorContextManager(_GeneratorContextManagerBase,
  139. AbstractAsyncContextManager):
  140. """Helper for @asynccontextmanager."""
  141. async def __aenter__(self):
  142. try:
  143. return await self.gen.__anext__()
  144. except StopAsyncIteration:
  145. raise RuntimeError("generator didn't yield") from None
  146. async def __aexit__(self, typ, value, traceback):
  147. if typ is None:
  148. try:
  149. await self.gen.__anext__()
  150. except StopAsyncIteration:
  151. return
  152. else:
  153. raise RuntimeError("generator didn't stop")
  154. else:
  155. if value is None:
  156. value = typ()
  157. # See _GeneratorContextManager.__exit__ for comments on subtleties
  158. # in this implementation
  159. try:
  160. await self.gen.athrow(typ, value, traceback)
  161. raise RuntimeError("generator didn't stop after athrow()")
  162. except StopAsyncIteration as exc:
  163. return exc is not value
  164. except RuntimeError as exc:
  165. if exc is value:
  166. return False
  167. # Avoid suppressing if a StopIteration exception
  168. # was passed to throw() and later wrapped into a RuntimeError
  169. # (see PEP 479 for sync generators; async generators also
  170. # have this behavior). But do this only if the exception wrapped
  171. # by the RuntimeError is actully Stop(Async)Iteration (see
  172. # issue29692).
  173. if isinstance(value, (StopIteration, StopAsyncIteration)):
  174. if exc.__cause__ is value:
  175. return False
  176. raise
  177. except BaseException as exc:
  178. if exc is not value:
  179. raise
  180. def contextmanager(func):
  181. """@contextmanager decorator.
  182. Typical usage:
  183. @contextmanager
  184. def some_generator(<arguments>):
  185. <setup>
  186. try:
  187. yield <value>
  188. finally:
  189. <cleanup>
  190. This makes this:
  191. with some_generator(<arguments>) as <variable>:
  192. <body>
  193. equivalent to this:
  194. <setup>
  195. try:
  196. <variable> = <value>
  197. <body>
  198. finally:
  199. <cleanup>
  200. """
  201. @wraps(func)
  202. def helper(*args, **kwds):
  203. return _GeneratorContextManager(func, args, kwds)
  204. return helper
  205. def asynccontextmanager(func):
  206. """@asynccontextmanager decorator.
  207. Typical usage:
  208. @asynccontextmanager
  209. async def some_async_generator(<arguments>):
  210. <setup>
  211. try:
  212. yield <value>
  213. finally:
  214. <cleanup>
  215. This makes this:
  216. async with some_async_generator(<arguments>) as <variable>:
  217. <body>
  218. equivalent to this:
  219. <setup>
  220. try:
  221. <variable> = <value>
  222. <body>
  223. finally:
  224. <cleanup>
  225. """
  226. @wraps(func)
  227. def helper(*args, **kwds):
  228. return _AsyncGeneratorContextManager(func, args, kwds)
  229. return helper
  230. class closing(AbstractContextManager):
  231. """Context to automatically close something at the end of a block.
  232. Code like this:
  233. with closing(<module>.open(<arguments>)) as f:
  234. <block>
  235. is equivalent to this:
  236. f = <module>.open(<arguments>)
  237. try:
  238. <block>
  239. finally:
  240. f.close()
  241. """
  242. def __init__(self, thing):
  243. self.thing = thing
  244. def __enter__(self):
  245. return self.thing
  246. def __exit__(self, *exc_info):
  247. self.thing.close()
  248. class _RedirectStream(AbstractContextManager):
  249. _stream = None
  250. def __init__(self, new_target):
  251. self._new_target = new_target
  252. # We use a list of old targets to make this CM re-entrant
  253. self._old_targets = []
  254. def __enter__(self):
  255. self._old_targets.append(getattr(sys, self._stream))
  256. setattr(sys, self._stream, self._new_target)
  257. return self._new_target
  258. def __exit__(self, exctype, excinst, exctb):
  259. setattr(sys, self._stream, self._old_targets.pop())
  260. class redirect_stdout(_RedirectStream):
  261. """Context manager for temporarily redirecting stdout to another file.
  262. # How to send help() to stderr
  263. with redirect_stdout(sys.stderr):
  264. help(dir)
  265. # How to write help() to a file
  266. with open('help.txt', 'w') as f:
  267. with redirect_stdout(f):
  268. help(pow)
  269. """
  270. _stream = "stdout"
  271. class redirect_stderr(_RedirectStream):
  272. """Context manager for temporarily redirecting stderr to another file."""
  273. _stream = "stderr"
  274. class suppress(AbstractContextManager):
  275. """Context manager to suppress specified exceptions
  276. After the exception is suppressed, execution proceeds with the next
  277. statement following the with statement.
  278. with suppress(FileNotFoundError):
  279. os.remove(somefile)
  280. # Execution still resumes here if the file was already removed
  281. """
  282. def __init__(self, *exceptions):
  283. self._exceptions = exceptions
  284. def __enter__(self):
  285. pass
  286. def __exit__(self, exctype, excinst, exctb):
  287. # Unlike isinstance and issubclass, CPython exception handling
  288. # currently only looks at the concrete type hierarchy (ignoring
  289. # the instance and subclass checking hooks). While Guido considers
  290. # that a bug rather than a feature, it's a fairly hard one to fix
  291. # due to various internal implementation details. suppress provides
  292. # the simpler issubclass based semantics, rather than trying to
  293. # exactly reproduce the limitations of the CPython interpreter.
  294. #
  295. # See http://bugs.python.org/issue12029 for more details
  296. return exctype is not None and issubclass(exctype, self._exceptions)
  297. class _BaseExitStack:
  298. """A base class for ExitStack and AsyncExitStack."""
  299. @staticmethod
  300. def _create_exit_wrapper(cm, cm_exit):
  301. return MethodType(cm_exit, cm)
  302. @staticmethod
  303. def _create_cb_wrapper(callback, /, *args, **kwds):
  304. def _exit_wrapper(exc_type, exc, tb):
  305. callback(*args, **kwds)
  306. return _exit_wrapper
  307. def __init__(self):
  308. self._exit_callbacks = deque()
  309. def pop_all(self):
  310. """Preserve the context stack by transferring it to a new instance."""
  311. new_stack = type(self)()
  312. new_stack._exit_callbacks = self._exit_callbacks
  313. self._exit_callbacks = deque()
  314. return new_stack
  315. def push(self, exit):
  316. """Registers a callback with the standard __exit__ method signature.
  317. Can suppress exceptions the same way __exit__ method can.
  318. Also accepts any object with an __exit__ method (registering a call
  319. to the method instead of the object itself).
  320. """
  321. # We use an unbound method rather than a bound method to follow
  322. # the standard lookup behaviour for special methods.
  323. _cb_type = type(exit)
  324. try:
  325. exit_method = _cb_type.__exit__
  326. except AttributeError:
  327. # Not a context manager, so assume it's a callable.
  328. self._push_exit_callback(exit)
  329. else:
  330. self._push_cm_exit(exit, exit_method)
  331. return exit # Allow use as a decorator.
  332. def enter_context(self, cm):
  333. """Enters the supplied context manager.
  334. If successful, also pushes its __exit__ method as a callback and
  335. returns the result of the __enter__ method.
  336. """
  337. # We look up the special methods on the type to match the with
  338. # statement.
  339. _cm_type = type(cm)
  340. _exit = _cm_type.__exit__
  341. result = _cm_type.__enter__(cm)
  342. self._push_cm_exit(cm, _exit)
  343. return result
  344. def callback(self, callback, /, *args, **kwds):
  345. """Registers an arbitrary callback and arguments.
  346. Cannot suppress exceptions.
  347. """
  348. _exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds)
  349. # We changed the signature, so using @wraps is not appropriate, but
  350. # setting __wrapped__ may still help with introspection.
  351. _exit_wrapper.__wrapped__ = callback
  352. self._push_exit_callback(_exit_wrapper)
  353. return callback # Allow use as a decorator
  354. def _push_cm_exit(self, cm, cm_exit):
  355. """Helper to correctly register callbacks to __exit__ methods."""
  356. _exit_wrapper = self._create_exit_wrapper(cm, cm_exit)
  357. self._push_exit_callback(_exit_wrapper, True)
  358. def _push_exit_callback(self, callback, is_sync=True):
  359. self._exit_callbacks.append((is_sync, callback))
  360. # Inspired by discussions on http://bugs.python.org/issue13585
  361. class ExitStack(_BaseExitStack, AbstractContextManager):
  362. """Context manager for dynamic management of a stack of exit callbacks.
  363. For example:
  364. with ExitStack() as stack:
  365. files = [stack.enter_context(open(fname)) for fname in filenames]
  366. # All opened files will automatically be closed at the end of
  367. # the with statement, even if attempts to open files later
  368. # in the list raise an exception.
  369. """
  370. def __enter__(self):
  371. return self
  372. def __exit__(self, *exc_details):
  373. received_exc = exc_details[0] is not None
  374. # We manipulate the exception state so it behaves as though
  375. # we were actually nesting multiple with statements
  376. frame_exc = sys.exc_info()[1]
  377. def _fix_exception_context(new_exc, old_exc):
  378. # Context may not be correct, so find the end of the chain
  379. while 1:
  380. exc_context = new_exc.__context__
  381. if exc_context is old_exc:
  382. # Context is already set correctly (see issue 20317)
  383. return
  384. if exc_context is None or exc_context is frame_exc:
  385. break
  386. new_exc = exc_context
  387. # Change the end of the chain to point to the exception
  388. # we expect it to reference
  389. new_exc.__context__ = old_exc
  390. # Callbacks are invoked in LIFO order to match the behaviour of
  391. # nested context managers
  392. suppressed_exc = False
  393. pending_raise = False
  394. while self._exit_callbacks:
  395. is_sync, cb = self._exit_callbacks.pop()
  396. assert is_sync
  397. try:
  398. if cb(*exc_details):
  399. suppressed_exc = True
  400. pending_raise = False
  401. exc_details = (None, None, None)
  402. except:
  403. new_exc_details = sys.exc_info()
  404. # simulate the stack of exceptions by setting the context
  405. _fix_exception_context(new_exc_details[1], exc_details[1])
  406. pending_raise = True
  407. exc_details = new_exc_details
  408. if pending_raise:
  409. try:
  410. # bare "raise exc_details[1]" replaces our carefully
  411. # set-up context
  412. fixed_ctx = exc_details[1].__context__
  413. raise exc_details[1]
  414. except BaseException:
  415. exc_details[1].__context__ = fixed_ctx
  416. raise
  417. return received_exc and suppressed_exc
  418. def close(self):
  419. """Immediately unwind the context stack."""
  420. self.__exit__(None, None, None)
  421. # Inspired by discussions on https://bugs.python.org/issue29302
  422. class AsyncExitStack(_BaseExitStack, AbstractAsyncContextManager):
  423. """Async context manager for dynamic management of a stack of exit
  424. callbacks.
  425. For example:
  426. async with AsyncExitStack() as stack:
  427. connections = [await stack.enter_async_context(get_connection())
  428. for i in range(5)]
  429. # All opened connections will automatically be released at the
  430. # end of the async with statement, even if attempts to open a
  431. # connection later in the list raise an exception.
  432. """
  433. @staticmethod
  434. def _create_async_exit_wrapper(cm, cm_exit):
  435. return MethodType(cm_exit, cm)
  436. @staticmethod
  437. def _create_async_cb_wrapper(callback, /, *args, **kwds):
  438. async def _exit_wrapper(exc_type, exc, tb):
  439. await callback(*args, **kwds)
  440. return _exit_wrapper
  441. async def enter_async_context(self, cm):
  442. """Enters the supplied async context manager.
  443. If successful, also pushes its __aexit__ method as a callback and
  444. returns the result of the __aenter__ method.
  445. """
  446. _cm_type = type(cm)
  447. _exit = _cm_type.__aexit__
  448. result = await _cm_type.__aenter__(cm)
  449. self._push_async_cm_exit(cm, _exit)
  450. return result
  451. def push_async_exit(self, exit):
  452. """Registers a coroutine function with the standard __aexit__ method
  453. signature.
  454. Can suppress exceptions the same way __aexit__ method can.
  455. Also accepts any object with an __aexit__ method (registering a call
  456. to the method instead of the object itself).
  457. """
  458. _cb_type = type(exit)
  459. try:
  460. exit_method = _cb_type.__aexit__
  461. except AttributeError:
  462. # Not an async context manager, so assume it's a coroutine function
  463. self._push_exit_callback(exit, False)
  464. else:
  465. self._push_async_cm_exit(exit, exit_method)
  466. return exit # Allow use as a decorator
  467. def push_async_callback(self, callback, /, *args, **kwds):
  468. """Registers an arbitrary coroutine function and arguments.
  469. Cannot suppress exceptions.
  470. """
  471. _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds)
  472. # We changed the signature, so using @wraps is not appropriate, but
  473. # setting __wrapped__ may still help with introspection.
  474. _exit_wrapper.__wrapped__ = callback
  475. self._push_exit_callback(_exit_wrapper, False)
  476. return callback # Allow use as a decorator
  477. async def aclose(self):
  478. """Immediately unwind the context stack."""
  479. await self.__aexit__(None, None, None)
  480. def _push_async_cm_exit(self, cm, cm_exit):
  481. """Helper to correctly register coroutine function to __aexit__
  482. method."""
  483. _exit_wrapper = self._create_async_exit_wrapper(cm, cm_exit)
  484. self._push_exit_callback(_exit_wrapper, False)
  485. async def __aenter__(self):
  486. return self
  487. async def __aexit__(self, *exc_details):
  488. received_exc = exc_details[0] is not None
  489. # We manipulate the exception state so it behaves as though
  490. # we were actually nesting multiple with statements
  491. frame_exc = sys.exc_info()[1]
  492. def _fix_exception_context(new_exc, old_exc):
  493. # Context may not be correct, so find the end of the chain
  494. while 1:
  495. exc_context = new_exc.__context__
  496. if exc_context is old_exc:
  497. # Context is already set correctly (see issue 20317)
  498. return
  499. if exc_context is None or exc_context is frame_exc:
  500. break
  501. new_exc = exc_context
  502. # Change the end of the chain to point to the exception
  503. # we expect it to reference
  504. new_exc.__context__ = old_exc
  505. # Callbacks are invoked in LIFO order to match the behaviour of
  506. # nested context managers
  507. suppressed_exc = False
  508. pending_raise = False
  509. while self._exit_callbacks:
  510. is_sync, cb = self._exit_callbacks.pop()
  511. try:
  512. if is_sync:
  513. cb_suppress = cb(*exc_details)
  514. else:
  515. cb_suppress = await cb(*exc_details)
  516. if cb_suppress:
  517. suppressed_exc = True
  518. pending_raise = False
  519. exc_details = (None, None, None)
  520. except:
  521. new_exc_details = sys.exc_info()
  522. # simulate the stack of exceptions by setting the context
  523. _fix_exception_context(new_exc_details[1], exc_details[1])
  524. pending_raise = True
  525. exc_details = new_exc_details
  526. if pending_raise:
  527. try:
  528. # bare "raise exc_details[1]" replaces our carefully
  529. # set-up context
  530. fixed_ctx = exc_details[1].__context__
  531. raise exc_details[1]
  532. except BaseException:
  533. exc_details[1].__context__ = fixed_ctx
  534. raise
  535. return received_exc and suppressed_exc
  536. class nullcontext(AbstractContextManager):
  537. """Context manager that does no additional processing.
  538. Used as a stand-in for a normal context manager, when a particular
  539. block of code is only sometimes used with a normal context manager:
  540. cm = optional_cm if condition else nullcontext()
  541. with cm:
  542. # Perform operation, using optional_cm if condition is True
  543. """
  544. def __init__(self, enter_result=None):
  545. self.enter_result = enter_result
  546. def __enter__(self):
  547. return self.enter_result
  548. def __exit__(self, *excinfo):
  549. pass