././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1624775924.9167192 contextlib2-21.6.0/0000755000175100001710000000000000000000000013375 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/CONTRIBUTING.md0000644000175100001710000000046400000000000015632 0ustar00runnerdocker[![Jazzband](https://jazzband.co/static/img/jazzband.svg)](https://jazzband.co/) This is a [Jazzband](https://jazzband.co/) project. By contributing you agree to abide by the [Contributor Code of Conduct](https://jazzband.co/about/conduct) and follow the [guidelines](https://jazzband.co/about/guidelines). ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/LICENSE.txt0000644000175100001710000001421600000000000015224 0ustar00runnerdockerNote: The type hints included in this package come from the typeshed project, and are hence distributed under the Apache License 2.0 rather than under the Python Software License that covers the module implementation and test suite. A. HISTORY OF THE SOFTWARE ========================== contextlib2 is a derivative of the contextlib module distributed by the PSF as part of the Python standard library. According, it is itself redistributed under the PSF license (reproduced in full below). As the contextlib module was added only in Python 2.5, the licenses for earlier Python versions are not applicable and have not been included. Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands as a successor of a language called ABC. Guido remains Python's principal author, although it includes many contributions from others. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) in Reston, Virginia where he released several versions of the software. In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations (now Zope Corporation, see http://www.zope.com). In 2001, the Python Software Foundation (PSF, see http://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corporation is a sponsoring member of the PSF. All Python releases are Open Source (see http://www.opensource.org for the Open Source Definition). Historically, most, but not all, Python releases have also been GPL-compatible; the table below summarizes the various releases that included the contextlib module. Release Derived Year Owner GPL- from compatible? (1) 2.5 2.4 2006 PSF yes 2.5.1 2.5 2007 PSF yes 2.5.2 2.5.1 2008 PSF yes 2.5.3 2.5.2 2008 PSF yes 2.6 2.5 2008 PSF yes 2.6.1 2.6 2008 PSF yes 2.6.2 2.6.1 2009 PSF yes 2.6.3 2.6.2 2009 PSF yes 2.6.4 2.6.3 2009 PSF yes 2.6.5 2.6.4 2010 PSF yes 3.0 2.6 2008 PSF yes 3.0.1 3.0 2009 PSF yes 3.1 3.0.1 2009 PSF yes 3.1.1 3.1 2009 PSF yes 3.1.2 3.1.1 2010 PSF yes 3.1.3 3.1.2 2010 PSF yes 3.1.4 3.1.3 2011 PSF yes 3.2 3.1 2011 PSF yes 3.2.1 3.2 2011 PSF yes 3.2.2 3.2.1 2011 PSF yes 3.3 3.2 2012 PSF yes Footnotes: (1) GPL-compatible doesn't mean that we're distributing Python under the GPL. All Python licenses, unlike the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible licenses make it possible to combine Python with other software that is released under the GPL; the others don't. Thanks to the many outside volunteers who have worked under Guido's direction to make these releases possible. B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON =============================================================== PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 -------------------------------------------- 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python. 4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using Python, Licensee agrees to be bound by the terms and conditions of this License Agreement. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/MANIFEST.in0000644000175100001710000000032600000000000015134 0ustar00runnerdockerinclude *.py *.cfg *.txt *.rst *.md *.ini MANIFEST.in recursive-include contextlib2 *.py *.pyi py.typed recursive-include docs *.rst *.py make.bat Makefile recursive-include test *.py recursive-include dev *.patch ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/NEWS.rst0000644000175100001710000001421700000000000014710 0ustar00runnerdockerRelease History --------------- 21.6.0 (2021-06-27) ^^^^^^^^^^^^^^^^^^^ * License update: due to the inclusion of type hints from the ``typeshed`` project, the ``contextlib2`` project is now under a combination of the Python Software License (existing license) and the Apache License 2.0 (``typeshed`` license) * Switched to calendar based versioning using a "year"-"month"-"serial" scheme, rather than continuing with pre-1.0 semantic versioning * Due to the inclusion of asynchronous features from Python 3.7+, the minimum supported Python version is now Python 3.6 (`#29 `__) * Synchronised with the Python 3.10 version of contextlib (`#12 `__), making the following new features available on Python 3.6+: * ``asyncontextmanager`` (added in Python 3.7, enhanced in Python 3.10) * ``aclosing`` (added in Python 3.10) * ``AbstractAsyncContextManager`` (added in Python 3.7) * ``AsyncContextDecorator`` (added in Python 3.10) * ``AsyncExitStack`` (added in Python 3.7) * async support in ``nullcontext`` (Python 3.10) * ``contextlib2`` now includes an adapted copy of the ``contextlib`` type hints from ``typeshed`` (the adaptation removes the Python version dependencies from the API definition) (`#33 `__) * to incorporate the type hints stub file and the ``py.typed`` marker file, ``contextlib2`` is now installed as a package rather than as a module * Updates to the default compatibility testing matrix: * Added: CPython 3.9, CPython 3.10 * Dropped: CPython 2.7, CPython 3.5, PyPy2 0.6.0.post1 (2019-10-10) ^^^^^^^^^^^^^^^^^^^^^^^^ * Issue `#24 `__: Correctly update NEWS.rst for the 0.6.0 release. 0.6.0 (2019-09-21) ^^^^^^^^^^^^^^^^^^ * Issue `#16 `__: Backport `AbstractContextManager` from Python 3.6 and `nullcontext` from Python 3.7 (patch by John Vandenberg) 0.5.5 (2017-04-25) ^^^^^^^^^^^^^^^^^^ * Issue `#13 `__: ``setup.py`` now falls back to plain ``distutils`` if ``setuptools`` is not available (patch by Allan Harwood) * Updates to the default compatibility testing matrix: * Added: PyPy3, CPython 3.6 (maintenance), CPython 3.7 (development) * Dropped: CPython 3.3 0.5.4 (2016-07-31) ^^^^^^^^^^^^^^^^^^ * Thanks to the welcome efforts of Jannis Leidel, contextlib2 is now a [Jazzband](https://jazzband.co/) project! This means that I (Nick Coghlan) am no longer a single point of failure for backports of future contextlib updates to earlier Python versions. * Issue `#7 `__: Backported fix for CPython issue `#27122 `__, preventing a potential infinite loop on Python 3.5 when handling ``RuntimeError`` (CPython updates by Gregory P. Smith & Serhiy Storchaka) 0.5.3 (2016-05-02) ^^^^^^^^^^^^^^^^^^ * ``ExitStack`` now correctly handles context managers implemented as old-style classes in Python 2.x (such as ``codecs.StreamReader`` and ``codecs.StreamWriter``) * ``setup.py`` has been migrated to setuptools and configured to emit a universal wheel file by default 0.5.2 (2016-05-02) ^^^^^^^^^^^^^^^^^^ * development migrated from BitBucket to GitHub * ``redirect_stream``, ``redirect_stdout``, ``redirect_stderr`` and ``suppress`` now explicitly inherit from ``object``, ensuring compatibility with ``ExitStack`` when run under Python 2.x (patch contributed by Devin Jeanpierre). * ``MANIFEST.in`` is now included in the published sdist, ensuring the archive can be precisely recreated even without access to the original source repo (patch contributed by Guy Rozendorn) 0.5.1 (2016-01-13) ^^^^^^^^^^^^^^^^^^ * Python 2.6 compatilibity restored (patch contributed by Armin Ronacher) * README converted back to reStructured Text formatting 0.5.0 (2016-01-12) ^^^^^^^^^^^^^^^^^^ * Updated to include all features from the Python 3.4 and 3.5 releases of contextlib (also includes some ``ExitStack`` enhancements made following the integration into the standard library for Python 3.3) * The legacy ``ContextStack`` and ``ContextDecorator.refresh_cm`` APIs are no longer documented and emit ``DeprecationWarning`` when used * Python 2.6, 3.2 and 3.3 have been dropped from compatibility testing * tox is now supported for local version compatibility testing (patch by Marc Abramowitz) 0.4.0 (2012-05-05) ^^^^^^^^^^^^^^^^^^ * (BitBucket) Issue #8: Replace ContextStack with ExitStack (old ContextStack API retained for backwards compatibility) * Fall back to unittest2 if unittest is missing required functionality 0.3.1 (2012-01-17) ^^^^^^^^^^^^^^^^^^ * (BitBucket) Issue #7: Add MANIFEST.in so PyPI package contains all relevant files (patch contributed by Doug Latornell) 0.3 (2012-01-04) ^^^^^^^^^^^^^^^^ * (BitBucket) Issue #5: ContextStack.register no longer pointlessly returns the wrapped function * (BitBucket) Issue #2: Add examples and recipes section to docs * (BitBucket) Issue #3: ContextStack.register_exit() now accepts objects with __exit__ attributes in addition to accepting exit callbacks directly * (BitBucket) Issue #1: Add ContextStack.preserve() to move all registered callbacks to a new ContextStack object * Wrapped callbacks now expose __wrapped__ (for direct callbacks) or __self__ (for context manager methods) attributes to aid in introspection * Moved version number to a VERSION.txt file (read by both docs and setup.py) * Added NEWS.rst (and incorporated into documentation) 0.2 (2011-12-15) ^^^^^^^^^^^^^^^^ * Renamed CleanupManager to ContextStack (hopefully before anyone started using the module for anything, since I didn't alias the old name at all) 0.1 (2011-12-13) ^^^^^^^^^^^^^^^^ * Initial release as a backport module * Added CleanupManager (based on a `Python feature request`_) * Added ContextDecorator.refresh_cm() (based on a `Python tracker issue`_) .. _Python feature request: http://bugs.python.org/issue13585 .. _Python tracker issue: http://bugs.python.org/issue11647 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1624775924.9167192 contextlib2-21.6.0/PKG-INFO0000644000175100001710000000777100000000000014506 0ustar00runnerdockerMetadata-Version: 2.1 Name: contextlib2 Version: 21.6.0 Summary: Backports and enhancements for the contextlib module Home-page: http://contextlib2.readthedocs.org Author: Nick Coghlan Author-email: ncoghlan@gmail.com License: PSF License Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: License :: OSI Approved :: Apache Software License Classifier: License :: OSI Approved :: Python Software Foundation License Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Requires-Python: >=3.6 License-File: LICENSE.txt .. image:: https://jazzband.co/static/img/badge.svg :target: https://jazzband.co/ :alt: Jazzband .. image:: https://github.com/jazzband/contextlib2/workflows/Test/badge.svg :target: https://github.com/jazzband/contextlib2/actions :alt: Tests .. image:: https://codecov.io/gh/jazzband/contextlib2/branch/master/graph/badge.svg :target: https://codecov.io/gh/jazzband/contextlib2 :alt: Coverage .. image:: https://readthedocs.org/projects/contextlib2/badge/?version=latest :target: https://contextlib2.readthedocs.org/ :alt: Latest Docs contextlib2 is a backport of the `standard library's contextlib module `_ to earlier Python versions. It also sometimes serves as a real world proving ground for possible future enhancements to the standard library version. Licensing --------- As a backport of Python standard library software, the implementation, test suite and other supporting files for this project are distributed under the Python Software License used for the CPython reference implementation. The one exception is the included type hints file, which comes from the ``typeshed`` project, and is hence distributed under the Apache License 2.0. Development ----------- contextlib2 has no runtime dependencies, but requires ``setuptools`` and ``wheel`` at build time to generate universal wheel archives. Local testing is a matter of running:: python3 -m unittest discover -t . -s test You can test against multiple versions of Python with `tox `_:: pip install tox tox Versions currently tested in both tox and GitHub Actions are: * CPython 3.6 * CPython 3.7 * CPython 3.8 * CPython 3.9 * CPython 3.10 * PyPy3 Updating to a new stdlib reference version ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ As of Python 3.10, 4 files needed to be copied from the CPython reference implementation to contextlib2: * ``Doc/contextlib.rst`` -> ``docs/contextlib2.rst`` * ``Lib/contextlib.py`` -> ``contextlib2/__init__.py`` * ``Lib/test/test_contextlib.py`` -> ``test/test_contextlib.py`` * ``Lib/test/test_contextlib_async.py`` -> ``test/test_contextlib_async.py`` The corresponding version of ``contextlib2/__init__.pyi`` also needs to be retrieved from the ``typeshed`` project:: wget https://raw.githubusercontent.com/python/typeshed/master/stdlib/contextlib.pyi For the 3.10 sync, the only changes needed to the test files were to import from ``contextlib2`` rather than ``contextlib``. The test directory is laid out so that the test suite's imports from ``test.support`` work the same way they do in the main CPython test suite. The following patch files are saved in the ``dev`` directory: * changes made to ``contextlib2/__init__.py`` to get it to run on the older versions (and to add back in the deprecated APIs that never graduated to the standard library version) * changes made to ``contextlib2/__init__.pyi`` to make the Python version guards unconditional (since the ``contextlib2`` API is the same on all supported versions) * changes made to ``docs/contextlib2.rst`` to use ``contextlib2`` version numbers in the version added/changed notes and to integrate the module documentation with the rest of the project documentation ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/README.rst0000644000175100001710000000633000000000000015066 0ustar00runnerdocker.. image:: https://jazzband.co/static/img/badge.svg :target: https://jazzband.co/ :alt: Jazzband .. image:: https://github.com/jazzband/contextlib2/workflows/Test/badge.svg :target: https://github.com/jazzband/contextlib2/actions :alt: Tests .. image:: https://codecov.io/gh/jazzband/contextlib2/branch/master/graph/badge.svg :target: https://codecov.io/gh/jazzband/contextlib2 :alt: Coverage .. image:: https://readthedocs.org/projects/contextlib2/badge/?version=latest :target: https://contextlib2.readthedocs.org/ :alt: Latest Docs contextlib2 is a backport of the `standard library's contextlib module `_ to earlier Python versions. It also sometimes serves as a real world proving ground for possible future enhancements to the standard library version. Licensing --------- As a backport of Python standard library software, the implementation, test suite and other supporting files for this project are distributed under the Python Software License used for the CPython reference implementation. The one exception is the included type hints file, which comes from the ``typeshed`` project, and is hence distributed under the Apache License 2.0. Development ----------- contextlib2 has no runtime dependencies, but requires ``setuptools`` and ``wheel`` at build time to generate universal wheel archives. Local testing is a matter of running:: python3 -m unittest discover -t . -s test You can test against multiple versions of Python with `tox `_:: pip install tox tox Versions currently tested in both tox and GitHub Actions are: * CPython 3.6 * CPython 3.7 * CPython 3.8 * CPython 3.9 * CPython 3.10 * PyPy3 Updating to a new stdlib reference version ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ As of Python 3.10, 4 files needed to be copied from the CPython reference implementation to contextlib2: * ``Doc/contextlib.rst`` -> ``docs/contextlib2.rst`` * ``Lib/contextlib.py`` -> ``contextlib2/__init__.py`` * ``Lib/test/test_contextlib.py`` -> ``test/test_contextlib.py`` * ``Lib/test/test_contextlib_async.py`` -> ``test/test_contextlib_async.py`` The corresponding version of ``contextlib2/__init__.pyi`` also needs to be retrieved from the ``typeshed`` project:: wget https://raw.githubusercontent.com/python/typeshed/master/stdlib/contextlib.pyi For the 3.10 sync, the only changes needed to the test files were to import from ``contextlib2`` rather than ``contextlib``. The test directory is laid out so that the test suite's imports from ``test.support`` work the same way they do in the main CPython test suite. The following patch files are saved in the ``dev`` directory: * changes made to ``contextlib2/__init__.py`` to get it to run on the older versions (and to add back in the deprecated APIs that never graduated to the standard library version) * changes made to ``contextlib2/__init__.pyi`` to make the Python version guards unconditional (since the ``contextlib2`` API is the same on all supported versions) * changes made to ``docs/contextlib2.rst`` to use ``contextlib2`` version numbers in the version added/changed notes and to integrate the module documentation with the rest of the project documentation ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/VERSION.txt0000644000175100001710000000000700000000000015260 0ustar00runnerdocker21.6.0 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1624775924.9167192 contextlib2-21.6.0/contextlib2/0000755000175100001710000000000000000000000015632 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/contextlib2/__init__.py0000644000175100001710000006600500000000000017752 0ustar00runnerdocker"""contextlib2 - backports and enhancements to the contextlib module""" import abc import sys import warnings import _collections_abc from collections import deque from functools import wraps from types import MethodType # Python 3.6/3.7/3.8 compatibility: GenericAlias may not be defined try: from types import GenericAlias except ImportError: # If the real GenericAlias type doesn't exist, __class_getitem__ won't be used, # so the fallback placeholder doesn't need to provide any meaningful behaviour class GenericAlias: pass __all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext", "AbstractContextManager", "AbstractAsyncContextManager", "AsyncExitStack", "ContextDecorator", "ExitStack", "redirect_stdout", "redirect_stderr", "suppress", "aclosing"] # Backwards compatibility __all__ += ["ContextStack"] class AbstractContextManager(abc.ABC): """An abstract base class for context managers.""" __class_getitem__ = classmethod(GenericAlias) def __enter__(self): """Return `self` upon entering the runtime context.""" return self @abc.abstractmethod def __exit__(self, exc_type, exc_value, traceback): """Raise any exception triggered within the runtime context.""" return None @classmethod def __subclasshook__(cls, C): if cls is AbstractContextManager: return _collections_abc._check_methods(C, "__enter__", "__exit__") return NotImplemented class AbstractAsyncContextManager(abc.ABC): """An abstract base class for asynchronous context managers.""" __class_getitem__ = classmethod(GenericAlias) async def __aenter__(self): """Return `self` upon entering the runtime context.""" return self @abc.abstractmethod async def __aexit__(self, exc_type, exc_value, traceback): """Raise any exception triggered within the runtime context.""" return None @classmethod def __subclasshook__(cls, C): if cls is AbstractAsyncContextManager: return _collections_abc._check_methods(C, "__aenter__", "__aexit__") return NotImplemented class ContextDecorator(object): "A base class or mixin that enables context managers to work as decorators." def refresh_cm(self): """Returns the context manager used to actually wrap the call to the decorated function. The default implementation just returns *self*. Overriding this method allows otherwise one-shot context managers like _GeneratorContextManager to support use as decorators via implicit recreation. DEPRECATED: refresh_cm was never added to the standard library's ContextDecorator API """ warnings.warn("refresh_cm was never added to the standard library", DeprecationWarning) return self._recreate_cm() def _recreate_cm(self): """Return a recreated instance of self. Allows an otherwise one-shot context manager like _GeneratorContextManager to support use as a decorator via implicit recreation. This is a private interface just for _GeneratorContextManager. See issue #11647 for details. """ return self def __call__(self, func): @wraps(func) def inner(*args, **kwds): with self._recreate_cm(): return func(*args, **kwds) return inner class AsyncContextDecorator(object): "A base class or mixin that enables async context managers to work as decorators." def _recreate_cm(self): """Return a recreated instance of self. """ return self def __call__(self, func): @wraps(func) async def inner(*args, **kwds): async with self._recreate_cm(): return await func(*args, **kwds) return inner class _GeneratorContextManagerBase: """Shared functionality for @contextmanager and @asynccontextmanager.""" def __init__(self, func, args, kwds): self.gen = func(*args, **kwds) self.func, self.args, self.kwds = func, args, kwds # Issue 19330: ensure context manager instances have good docstrings doc = getattr(func, "__doc__", None) if doc is None: doc = type(self).__doc__ self.__doc__ = doc # Unfortunately, this still doesn't provide good help output when # inspecting the created context manager instances, since pydoc # currently bypasses the instance docstring and shows the docstring # for the class instead. # See http://bugs.python.org/issue19404 for more details. class _GeneratorContextManager(_GeneratorContextManagerBase, AbstractContextManager, ContextDecorator): """Helper for @contextmanager decorator.""" def _recreate_cm(self): # _GCM instances are one-shot context managers, so the # CM must be recreated each time a decorated function is # called return self.__class__(self.func, self.args, self.kwds) def __enter__(self): # do not keep args and kwds alive unnecessarily # they are only needed for recreation, which is not possible anymore del self.args, self.kwds, self.func try: return next(self.gen) except StopIteration: raise RuntimeError("generator didn't yield") from None def __exit__(self, type, value, traceback): if type is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = type() try: self.gen.throw(type, value, traceback) except StopIteration as exc: # Suppress StopIteration *unless* it's the same exception that # was passed to throw(). This prevents a StopIteration # raised inside the "with" statement from being suppressed. return exc is not value except RuntimeError as exc: # Don't re-raise the passed in exception. (issue27122) if exc is value: return False # Likewise, avoid suppressing if a StopIteration exception # was passed to throw() and later wrapped into a RuntimeError # (see PEP 479). if type is StopIteration and exc.__cause__ is value: return False raise except: # only re-raise if it's *not* the exception that was # passed to throw(), because __exit__() must not raise # an exception unless __exit__() itself failed. But throw() # has to raise the exception to signal propagation, so this # fixes the impedance mismatch between the throw() protocol # and the __exit__() protocol. # # This cannot use 'except BaseException as exc' (as in the # async implementation) to maintain compatibility with # Python 2, where old-style class exceptions are not caught # by 'except BaseException'. if sys.exc_info()[1] is value: return False raise raise RuntimeError("generator didn't stop after throw()") class _AsyncGeneratorContextManager(_GeneratorContextManagerBase, AbstractAsyncContextManager, AsyncContextDecorator): """Helper for @asynccontextmanager.""" def _recreate_cm(self): # _AGCM instances are one-shot context managers, so the # ACM must be recreated each time a decorated function is # called return self.__class__(self.func, self.args, self.kwds) async def __aenter__(self): try: return await self.gen.__anext__() except StopAsyncIteration: raise RuntimeError("generator didn't yield") from None async def __aexit__(self, typ, value, traceback): if typ is None: try: await self.gen.__anext__() except StopAsyncIteration: return else: raise RuntimeError("generator didn't stop") else: if value is None: value = typ() # See _GeneratorContextManager.__exit__ for comments on subtleties # in this implementation try: await self.gen.athrow(typ, value, traceback) raise RuntimeError("generator didn't stop after athrow()") except StopAsyncIteration as exc: return exc is not value except RuntimeError as exc: if exc is value: return False # Avoid suppressing if a StopIteration exception # was passed to throw() and later wrapped into a RuntimeError # (see PEP 479 for sync generators; async generators also # have this behavior). But do this only if the exception wrapped # by the RuntimeError is actually Stop(Async)Iteration (see # issue29692). if isinstance(value, (StopIteration, StopAsyncIteration)): if exc.__cause__ is value: return False raise except BaseException as exc: if exc is not value: raise def contextmanager(func): """@contextmanager decorator. Typical usage: @contextmanager def some_generator(): try: yield finally: This makes this: with some_generator() as : equivalent to this: try: = finally: """ @wraps(func) def helper(*args, **kwds): return _GeneratorContextManager(func, args, kwds) return helper def asynccontextmanager(func): """@asynccontextmanager decorator. Typical usage: @asynccontextmanager async def some_async_generator(): try: yield finally: This makes this: async with some_async_generator() as : equivalent to this: try: = finally: """ @wraps(func) def helper(*args, **kwds): return _AsyncGeneratorContextManager(func, args, kwds) return helper class closing(AbstractContextManager): """Context to automatically close something at the end of a block. Code like this: with closing(.open()) as f: is equivalent to this: f = .open() try: finally: f.close() """ def __init__(self, thing): self.thing = thing def __enter__(self): return self.thing def __exit__(self, *exc_info): self.thing.close() class aclosing(AbstractAsyncContextManager): """Async context manager for safely finalizing an asynchronously cleaned-up resource such as an async generator, calling its ``aclose()`` method. Code like this: async with aclosing(.fetch()) as agen: is equivalent to this: agen = .fetch() try: finally: await agen.aclose() """ def __init__(self, thing): self.thing = thing async def __aenter__(self): return self.thing async def __aexit__(self, *exc_info): await self.thing.aclose() class _RedirectStream(AbstractContextManager): _stream = None def __init__(self, new_target): self._new_target = new_target # We use a list of old targets to make this CM re-entrant self._old_targets = [] def __enter__(self): self._old_targets.append(getattr(sys, self._stream)) setattr(sys, self._stream, self._new_target) return self._new_target def __exit__(self, exctype, excinst, exctb): setattr(sys, self._stream, self._old_targets.pop()) class redirect_stdout(_RedirectStream): """Context manager for temporarily redirecting stdout to another file. # How to send help() to stderr with redirect_stdout(sys.stderr): help(dir) # How to write help() to a file with open('help.txt', 'w') as f: with redirect_stdout(f): help(pow) """ _stream = "stdout" class redirect_stderr(_RedirectStream): """Context manager for temporarily redirecting stderr to another file.""" _stream = "stderr" class suppress(AbstractContextManager): """Context manager to suppress specified exceptions After the exception is suppressed, execution proceeds with the next statement following the with statement. with suppress(FileNotFoundError): os.remove(somefile) # Execution still resumes here if the file was already removed """ def __init__(self, *exceptions): self._exceptions = exceptions def __enter__(self): pass def __exit__(self, exctype, excinst, exctb): # Unlike isinstance and issubclass, CPython exception handling # currently only looks at the concrete type hierarchy (ignoring # the instance and subclass checking hooks). While Guido considers # that a bug rather than a feature, it's a fairly hard one to fix # due to various internal implementation details. suppress provides # the simpler issubclass based semantics, rather than trying to # exactly reproduce the limitations of the CPython interpreter. # # See http://bugs.python.org/issue12029 for more details return exctype is not None and issubclass(exctype, self._exceptions) class _BaseExitStack: """A base class for ExitStack and AsyncExitStack.""" @staticmethod def _create_exit_wrapper(cm, cm_exit): return MethodType(cm_exit, cm) @staticmethod def _create_cb_wrapper(*args, **kwds): # Python 3.6/3.7 compatibility: no native positional-only args syntax callback, *args = args def _exit_wrapper(exc_type, exc, tb): callback(*args, **kwds) return _exit_wrapper def __init__(self): self._exit_callbacks = deque() def pop_all(self): """Preserve the context stack by transferring it to a new instance.""" new_stack = type(self)() new_stack._exit_callbacks = self._exit_callbacks self._exit_callbacks = deque() return new_stack def push(self, exit): """Registers a callback with the standard __exit__ method signature. Can suppress exceptions the same way __exit__ method can. Also accepts any object with an __exit__ method (registering a call to the method instead of the object itself). """ # We use an unbound method rather than a bound method to follow # the standard lookup behaviour for special methods. _cb_type = type(exit) try: exit_method = _cb_type.__exit__ except AttributeError: # Not a context manager, so assume it's a callable. self._push_exit_callback(exit) else: self._push_cm_exit(exit, exit_method) return exit # Allow use as a decorator. def enter_context(self, cm): """Enters the supplied context manager. If successful, also pushes its __exit__ method as a callback and returns the result of the __enter__ method. """ # We look up the special methods on the type to match the with # statement. _cm_type = type(cm) _exit = _cm_type.__exit__ result = _cm_type.__enter__(cm) self._push_cm_exit(cm, _exit) return result def callback(*args, **kwds): """Registers an arbitrary callback and arguments. Cannot suppress exceptions. """ # Python 3.6/3.7 compatibility: no native positional-only args syntax try: self, callback, *args = args except ValueError as exc: exc_details = str(exc).partition("(")[2] msg = "Not enough positional arguments {}".format(exc_details) raise TypeError(msg) from None _exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection. _exit_wrapper.__wrapped__ = callback self._push_exit_callback(_exit_wrapper) return callback # Allow use as a decorator def _push_cm_exit(self, cm, cm_exit): """Helper to correctly register callbacks to __exit__ methods.""" _exit_wrapper = self._create_exit_wrapper(cm, cm_exit) self._push_exit_callback(_exit_wrapper, True) def _push_exit_callback(self, callback, is_sync=True): self._exit_callbacks.append((is_sync, callback)) # Inspired by discussions on http://bugs.python.org/issue13585 class ExitStack(_BaseExitStack, AbstractContextManager): """Context manager for dynamic management of a stack of exit callbacks. For example: with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in filenames] # All opened files will automatically be closed at the end of # the with statement, even if attempts to open files later # in the list raise an exception. """ def __enter__(self): return self def __exit__(self, *exc_details): received_exc = exc_details[0] is not None # We manipulate the exception state so it behaves as though # we were actually nesting multiple with statements frame_exc = sys.exc_info()[1] def _fix_exception_context(new_exc, old_exc): # Context may not be correct, so find the end of the chain while 1: exc_context = new_exc.__context__ if exc_context is old_exc: # Context is already set correctly (see issue 20317) return if exc_context is None or exc_context is frame_exc: break new_exc = exc_context # Change the end of the chain to point to the exception # we expect it to reference new_exc.__context__ = old_exc # Callbacks are invoked in LIFO order to match the behaviour of # nested context managers suppressed_exc = False pending_raise = False while self._exit_callbacks: is_sync, cb = self._exit_callbacks.pop() assert is_sync try: if cb(*exc_details): suppressed_exc = True pending_raise = False exc_details = (None, None, None) except: new_exc_details = sys.exc_info() # simulate the stack of exceptions by setting the context _fix_exception_context(new_exc_details[1], exc_details[1]) pending_raise = True exc_details = new_exc_details if pending_raise: try: # bare "raise exc_details[1]" replaces our carefully # set-up context fixed_ctx = exc_details[1].__context__ raise exc_details[1] except BaseException: exc_details[1].__context__ = fixed_ctx raise return received_exc and suppressed_exc def close(self): """Immediately unwind the context stack.""" self.__exit__(None, None, None) # Inspired by discussions on https://bugs.python.org/issue29302 class AsyncExitStack(_BaseExitStack, AbstractAsyncContextManager): """Async context manager for dynamic management of a stack of exit callbacks. For example: async with AsyncExitStack() as stack: connections = [await stack.enter_async_context(get_connection()) for i in range(5)] # All opened connections will automatically be released at the # end of the async with statement, even if attempts to open a # connection later in the list raise an exception. """ @staticmethod def _create_async_exit_wrapper(cm, cm_exit): return MethodType(cm_exit, cm) @staticmethod def _create_async_cb_wrapper(*args, **kwds): # Python 3.6/3.7 compatibility: no native positional-only args syntax callback, *args = args async def _exit_wrapper(exc_type, exc, tb): await callback(*args, **kwds) return _exit_wrapper async def enter_async_context(self, cm): """Enters the supplied async context manager. If successful, also pushes its __aexit__ method as a callback and returns the result of the __aenter__ method. """ _cm_type = type(cm) _exit = _cm_type.__aexit__ result = await _cm_type.__aenter__(cm) self._push_async_cm_exit(cm, _exit) return result def push_async_exit(self, exit): """Registers a coroutine function with the standard __aexit__ method signature. Can suppress exceptions the same way __aexit__ method can. Also accepts any object with an __aexit__ method (registering a call to the method instead of the object itself). """ _cb_type = type(exit) try: exit_method = _cb_type.__aexit__ except AttributeError: # Not an async context manager, so assume it's a coroutine function self._push_exit_callback(exit, False) else: self._push_async_cm_exit(exit, exit_method) return exit # Allow use as a decorator def push_async_callback(*args, **kwds): """Registers an arbitrary coroutine function and arguments. Cannot suppress exceptions. """ # Python 3.6/3.7 compatibility: no native positional-only args syntax try: self, callback, *args = args except ValueError as exc: exc_details = str(exc).partition("(")[2] msg = "Not enough positional arguments {}".format(exc_details) raise TypeError(msg) from None _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection. _exit_wrapper.__wrapped__ = callback self._push_exit_callback(_exit_wrapper, False) return callback # Allow use as a decorator async def aclose(self): """Immediately unwind the context stack.""" await self.__aexit__(None, None, None) def _push_async_cm_exit(self, cm, cm_exit): """Helper to correctly register coroutine function to __aexit__ method.""" _exit_wrapper = self._create_async_exit_wrapper(cm, cm_exit) self._push_exit_callback(_exit_wrapper, False) async def __aenter__(self): return self async def __aexit__(self, *exc_details): received_exc = exc_details[0] is not None # We manipulate the exception state so it behaves as though # we were actually nesting multiple with statements frame_exc = sys.exc_info()[1] def _fix_exception_context(new_exc, old_exc): # Context may not be correct, so find the end of the chain while 1: exc_context = new_exc.__context__ if exc_context is old_exc: # Context is already set correctly (see issue 20317) return if exc_context is None or exc_context is frame_exc: break new_exc = exc_context # Change the end of the chain to point to the exception # we expect it to reference new_exc.__context__ = old_exc # Callbacks are invoked in LIFO order to match the behaviour of # nested context managers suppressed_exc = False pending_raise = False while self._exit_callbacks: is_sync, cb = self._exit_callbacks.pop() try: if is_sync: cb_suppress = cb(*exc_details) else: cb_suppress = await cb(*exc_details) if cb_suppress: suppressed_exc = True pending_raise = False exc_details = (None, None, None) except: new_exc_details = sys.exc_info() # simulate the stack of exceptions by setting the context _fix_exception_context(new_exc_details[1], exc_details[1]) pending_raise = True exc_details = new_exc_details if pending_raise: try: # bare "raise exc_details[1]" replaces our carefully # set-up context fixed_ctx = exc_details[1].__context__ raise exc_details[1] except BaseException: exc_details[1].__context__ = fixed_ctx raise return received_exc and suppressed_exc class nullcontext(AbstractContextManager, AbstractAsyncContextManager): """Context manager that does no additional processing. Used as a stand-in for a normal context manager, when a particular block of code is only sometimes used with a normal context manager: cm = optional_cm if condition else nullcontext() with cm: # Perform operation, using optional_cm if condition is True """ def __init__(self, enter_result=None): self.enter_result = enter_result def __enter__(self): return self.enter_result def __exit__(self, *excinfo): pass async def __aenter__(self): return self.enter_result async def __aexit__(self, *excinfo): pass # Preserve backwards compatibility class ContextStack(ExitStack): """Backwards compatibility alias for ExitStack""" def __init__(self): warnings.warn("ContextStack has been renamed to ExitStack", DeprecationWarning) super(ContextStack, self).__init__() def register_exit(self, callback): return self.push(callback) def register(self, callback, *args, **kwds): return self.callback(callback, *args, **kwds) def preserve(self): return self.pop_all() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/contextlib2/__init__.pyi0000644000175100001710000001207500000000000020121 0ustar00runnerdocker# Type hints copied from the typeshed project under the Apache License 2.0 # https://github.com/python/typeshed/blob/64c85cdd449ccaff90b546676220c9ecfa6e697f/LICENSE import sys from types import TracebackType from typing import ( IO, Any, AsyncContextManager, AsyncIterator, Awaitable, Callable, ContextManager, Iterator, Optional, Type, TypeVar, overload, ) from typing_extensions import ParamSpec, Protocol # contextlib2 API adaptation notes: # * the various 'if True:' guards replace sys.version checks in the original # typeshed file (those APIs are available on all supported versions) # * deliberately omitted APIs are listed in `dev/mypy.allowlist` # (e.g. deprecated experimental APIs that never graduated to the stdlib) AbstractContextManager = ContextManager if True: AbstractAsyncContextManager = AsyncContextManager _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _T_io = TypeVar("_T_io", bound=Optional[IO[str]]) _F = TypeVar("_F", bound=Callable[..., Any]) _P = ParamSpec("_P") _ExitFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] _CM_EF = TypeVar("_CM_EF", ContextManager[Any], _ExitFunc) class _GeneratorContextManager(ContextManager[_T_co]): def __call__(self, func: _F) -> _F: ... # type ignore to deal with incomplete ParamSpec support in mypy def contextmanager(func: Callable[_P, Iterator[_T]]) -> Callable[_P, _GeneratorContextManager[_T]]: ... # type: ignore if True: def asynccontextmanager(func: Callable[_P, AsyncIterator[_T]]) -> Callable[_P, AsyncContextManager[_T]]: ... # type: ignore class _SupportsClose(Protocol): def close(self) -> object: ... _SupportsCloseT = TypeVar("_SupportsCloseT", bound=_SupportsClose) class closing(ContextManager[_SupportsCloseT]): def __init__(self, thing: _SupportsCloseT) -> None: ... if True: class _SupportsAclose(Protocol): async def aclose(self) -> object: ... _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) class aclosing(AsyncContextManager[_SupportsAcloseT]): def __init__(self, thing: _SupportsAcloseT) -> None: ... _AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) class AsyncContextDecorator: def __call__(self, func: _AF) -> _AF: ... class suppress(ContextManager[None]): def __init__(self, *exceptions: Type[BaseException]) -> None: ... def __exit__( self, exctype: Optional[Type[BaseException]], excinst: Optional[BaseException], exctb: Optional[TracebackType] ) -> bool: ... class redirect_stdout(ContextManager[_T_io]): def __init__(self, new_target: _T_io) -> None: ... class redirect_stderr(ContextManager[_T_io]): def __init__(self, new_target: _T_io) -> None: ... class ContextDecorator: def __call__(self, func: _F) -> _F: ... _U = TypeVar("_U", bound=ExitStack) class ExitStack(ContextManager[ExitStack]): def __init__(self) -> None: ... def enter_context(self, cm: ContextManager[_T]) -> _T: ... def push(self, exit: _CM_EF) -> _CM_EF: ... def callback(self, callback: Callable[..., Any], *args: Any, **kwds: Any) -> Callable[..., Any]: ... def pop_all(self: _U) -> _U: ... def close(self) -> None: ... def __enter__(self: _U) -> _U: ... def __exit__( self, __exc_type: Optional[Type[BaseException]], __exc_value: Optional[BaseException], __traceback: Optional[TracebackType], ) -> bool: ... if True: _S = TypeVar("_S", bound=AsyncExitStack) _ExitCoroFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], Awaitable[bool]] _CallbackCoroFunc = Callable[..., Awaitable[Any]] _ACM_EF = TypeVar("_ACM_EF", AsyncContextManager[Any], _ExitCoroFunc) class AsyncExitStack(AsyncContextManager[AsyncExitStack]): def __init__(self) -> None: ... def enter_context(self, cm: ContextManager[_T]) -> _T: ... def enter_async_context(self, cm: AsyncContextManager[_T]) -> Awaitable[_T]: ... def push(self, exit: _CM_EF) -> _CM_EF: ... def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ... def callback(self, callback: Callable[..., Any], *args: Any, **kwds: Any) -> Callable[..., Any]: ... def push_async_callback(self, callback: _CallbackCoroFunc, *args: Any, **kwds: Any) -> _CallbackCoroFunc: ... def pop_all(self: _S) -> _S: ... def aclose(self) -> Awaitable[None]: ... def __aenter__(self: _S) -> Awaitable[_S]: ... def __aexit__( self, __exc_type: Optional[Type[BaseException]], __exc_value: Optional[BaseException], __traceback: Optional[TracebackType], ) -> Awaitable[bool]: ... if True: class nullcontext(AbstractContextManager[_T]): enter_result: _T @overload def __init__(self: nullcontext[None], enter_result: None = ...) -> None: ... @overload def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... def __enter__(self) -> _T: ... def __exit__(self, *exctype: Any) -> bool: ... ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/contextlib2/py.typed0000644000175100001710000000000000000000000017317 0ustar00runnerdocker././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1624775924.9167192 contextlib2-21.6.0/contextlib2.egg-info/0000755000175100001710000000000000000000000017324 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775924.0 contextlib2-21.6.0/contextlib2.egg-info/PKG-INFO0000644000175100001710000000777100000000000020435 0ustar00runnerdockerMetadata-Version: 2.1 Name: contextlib2 Version: 21.6.0 Summary: Backports and enhancements for the contextlib module Home-page: http://contextlib2.readthedocs.org Author: Nick Coghlan Author-email: ncoghlan@gmail.com License: PSF License Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: License :: OSI Approved :: Apache Software License Classifier: License :: OSI Approved :: Python Software Foundation License Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Requires-Python: >=3.6 License-File: LICENSE.txt .. image:: https://jazzband.co/static/img/badge.svg :target: https://jazzband.co/ :alt: Jazzband .. image:: https://github.com/jazzband/contextlib2/workflows/Test/badge.svg :target: https://github.com/jazzband/contextlib2/actions :alt: Tests .. image:: https://codecov.io/gh/jazzband/contextlib2/branch/master/graph/badge.svg :target: https://codecov.io/gh/jazzband/contextlib2 :alt: Coverage .. image:: https://readthedocs.org/projects/contextlib2/badge/?version=latest :target: https://contextlib2.readthedocs.org/ :alt: Latest Docs contextlib2 is a backport of the `standard library's contextlib module `_ to earlier Python versions. It also sometimes serves as a real world proving ground for possible future enhancements to the standard library version. Licensing --------- As a backport of Python standard library software, the implementation, test suite and other supporting files for this project are distributed under the Python Software License used for the CPython reference implementation. The one exception is the included type hints file, which comes from the ``typeshed`` project, and is hence distributed under the Apache License 2.0. Development ----------- contextlib2 has no runtime dependencies, but requires ``setuptools`` and ``wheel`` at build time to generate universal wheel archives. Local testing is a matter of running:: python3 -m unittest discover -t . -s test You can test against multiple versions of Python with `tox `_:: pip install tox tox Versions currently tested in both tox and GitHub Actions are: * CPython 3.6 * CPython 3.7 * CPython 3.8 * CPython 3.9 * CPython 3.10 * PyPy3 Updating to a new stdlib reference version ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ As of Python 3.10, 4 files needed to be copied from the CPython reference implementation to contextlib2: * ``Doc/contextlib.rst`` -> ``docs/contextlib2.rst`` * ``Lib/contextlib.py`` -> ``contextlib2/__init__.py`` * ``Lib/test/test_contextlib.py`` -> ``test/test_contextlib.py`` * ``Lib/test/test_contextlib_async.py`` -> ``test/test_contextlib_async.py`` The corresponding version of ``contextlib2/__init__.pyi`` also needs to be retrieved from the ``typeshed`` project:: wget https://raw.githubusercontent.com/python/typeshed/master/stdlib/contextlib.pyi For the 3.10 sync, the only changes needed to the test files were to import from ``contextlib2`` rather than ``contextlib``. The test directory is laid out so that the test suite's imports from ``test.support`` work the same way they do in the main CPython test suite. The following patch files are saved in the ``dev`` directory: * changes made to ``contextlib2/__init__.py`` to get it to run on the older versions (and to add back in the deprecated APIs that never graduated to the standard library version) * changes made to ``contextlib2/__init__.pyi`` to make the Python version guards unconditional (since the ``contextlib2`` API is the same on all supported versions) * changes made to ``docs/contextlib2.rst`` to use ``contextlib2`` version numbers in the version added/changed notes and to integrate the module documentation with the rest of the project documentation ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775924.0 contextlib2-21.6.0/contextlib2.egg-info/SOURCES.txt0000644000175100001710000000121400000000000021206 0ustar00runnerdockerCONTRIBUTING.md LICENSE.txt MANIFEST.in NEWS.rst README.rst VERSION.txt setup.cfg setup.py tox.ini contextlib2/__init__.py contextlib2/__init__.pyi contextlib2/py.typed contextlib2.egg-info/PKG-INFO contextlib2.egg-info/SOURCES.txt contextlib2.egg-info/dependency_links.txt contextlib2.egg-info/top_level.txt dev/py3_10_contextlib_pyi_to_contextlib2_pyi.patch dev/py3_10_contextlib_rst_to_contextlib2_rst.patch dev/py3_10_contextlib_to_contextlib2.patch docs/Makefile docs/conf.py docs/contextlib2.rst docs/index.rst docs/make.bat test/__init__.py test/test_contextlib.py test/test_contextlib_async.py test/support/__init__.py test/support/os_helper.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775924.0 contextlib2-21.6.0/contextlib2.egg-info/dependency_links.txt0000644000175100001710000000000100000000000023372 0ustar00runnerdocker ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775924.0 contextlib2-21.6.0/contextlib2.egg-info/top_level.txt0000644000175100001710000000001400000000000022051 0ustar00runnerdockercontextlib2 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1624775924.9167192 contextlib2-21.6.0/dev/0000755000175100001710000000000000000000000014153 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/dev/py3_10_contextlib_pyi_to_contextlib2_pyi.patch0000644000175100001710000000430200000000000025222 0ustar00runnerdocker--- ../contextlib.pyi 2021-06-27 16:02:28.004872421 +1000 +++ contextlib2/__init__.pyi 2021-06-27 16:00:25.431733524 +1000 @@ -1,3 +1,6 @@ +# Type hints copied from the typeshed project under the Apache License 2.0 +# https://github.com/python/typeshed/blob/64c85cdd449ccaff90b546676220c9ecfa6e697f/LICENSE + import sys from types import TracebackType from typing import ( @@ -16,8 +19,14 @@ ) from typing_extensions import ParamSpec, Protocol +# contextlib2 API adaptation notes: +# * the various 'if True:' guards replace sys.version checks in the original +# typeshed file (those APIs are available on all supported versions) +# * deliberately omitted APIs are listed in `dev/mypy.allowlist` +# (e.g. deprecated experimental APIs that never graduated to the stdlib) + AbstractContextManager = ContextManager -if sys.version_info >= (3, 7): +if True: AbstractAsyncContextManager = AsyncContextManager _T = TypeVar("_T") @@ -35,7 +44,7 @@ # type ignore to deal with incomplete ParamSpec support in mypy def contextmanager(func: Callable[_P, Iterator[_T]]) -> Callable[_P, _GeneratorContextManager[_T]]: ... # type: ignore -if sys.version_info >= (3, 7): +if True: def asynccontextmanager(func: Callable[_P, AsyncIterator[_T]]) -> Callable[_P, AsyncContextManager[_T]]: ... # type: ignore class _SupportsClose(Protocol): @@ -46,7 +55,7 @@ class closing(ContextManager[_SupportsCloseT]): def __init__(self, thing: _SupportsCloseT) -> None: ... -if sys.version_info >= (3, 10): +if True: class _SupportsAclose(Protocol): async def aclose(self) -> object: ... _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) @@ -88,7 +97,7 @@ __traceback: Optional[TracebackType], ) -> bool: ... -if sys.version_info >= (3, 7): +if True: _S = TypeVar("_S", bound=AsyncExitStack) _ExitCoroFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], Awaitable[bool]] @@ -112,7 +121,7 @@ __traceback: Optional[TracebackType], ) -> Awaitable[bool]: ... -if sys.version_info >= (3, 7): +if True: class nullcontext(AbstractContextManager[_T]): enter_result: _T @overload ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/dev/py3_10_contextlib_rst_to_contextlib2_rst.patch0000644000175100001710000001266300000000000025251 0ustar00runnerdocker--- ../cpython/Doc/library/contextlib.rst 2021-06-26 18:31:45.179532455 +1000 +++ docs/contextlib2.rst 2021-06-26 21:19:00.172517765 +1000 @@ -1,20 +1,5 @@ -:mod:`!contextlib` --- Utilities for :keyword:`!with`\ -statement contexts -========================================================================== - -.. module:: contextlib - :synopsis: Utilities for with-statement contexts. - -**Source code:** :source:`Lib/contextlib.py` - --------------- - -This module provides utilities for common tasks involving the :keyword:`with` -statement. For more information see also :ref:`typecontextmanager` and -:ref:`context-managers`. - - -Utilities ---------- +API Reference +------------- Functions and classes provided: @@ -26,8 +11,8 @@ ``self`` while :meth:`object.__exit__` is an abstract method which by default returns ``None``. See also the definition of :ref:`typecontextmanager`. - .. versionadded:: 3.6 - + .. versionadded:: 0.6.0 + Part of the standard library in Python 3.6 and later .. class:: AbstractAsyncContextManager @@ -38,8 +23,8 @@ returns ``None``. See also the definition of :ref:`async-context-managers`. - .. versionadded:: 3.7 - + .. versionadded:: 21.6.0 + Part of the standard library in Python 3.7 and later .. decorator:: contextmanager @@ -93,9 +78,6 @@ created by :func:`contextmanager` to meet the requirement that context managers support multiple invocations in order to be used as decorators). - .. versionchanged:: 3.2 - Use of :class:`ContextDecorator`. - .. decorator:: asynccontextmanager @@ -124,7 +106,10 @@ async with get_connection() as conn: return conn.query('SELECT ...') - .. versionadded:: 3.7 + .. versionadded:: 21.6.0 + Part of the standard library in Python 3.7 and later, enhanced in + Python 3.10 and later to allow created async context managers to be used + as async function decorators. Context managers defined with :func:`asynccontextmanager` can be used either as decorators or with :keyword:`async with` statements:: @@ -147,10 +132,6 @@ created by :func:`asynccontextmanager` to meet the requirement that context managers support multiple invocations in order to be used as decorators. - .. versionchanged:: 3.10 - Async context managers created with :func:`asynccontextmanager` can - be used as decorators. - .. function:: closing(thing) @@ -209,7 +190,8 @@ variables work as expected, and the exit code isn't run after the lifetime of some task it depends on). - .. versionadded:: 3.10 + .. versionadded:: 21.6.0 + Part of the standard library in Python 3.10 and later .. _simplifying-support-for-single-optional-context-managers: @@ -257,11 +239,11 @@ async with cm as session: # Send http requests with session - .. versionadded:: 3.7 - - .. versionchanged:: 3.10 - :term:`asynchronous context manager` support was added. + .. versionadded:: 0.6.0 + Part of the standard library in Python 3.7 and later + .. versionchanged:: 21.6.0 + Updated to Python 3.10 version with :term:`asynchronous context manager` support .. function:: suppress(*exceptions) @@ -300,7 +282,8 @@ This context manager is :ref:`reentrant `. - .. versionadded:: 3.4 + .. versionadded:: 0.5 + Part of the standard library in Python 3.4 and later .. function:: redirect_stdout(new_target) @@ -340,7 +323,8 @@ This context manager is :ref:`reentrant `. - .. versionadded:: 3.4 + .. versionadded:: 0.5 + Part of the standard library in Python 3.4 and later .. function:: redirect_stderr(new_target) @@ -350,7 +334,8 @@ This context manager is :ref:`reentrant `. - .. versionadded:: 3.5 + .. versionadded:: 0.5 + Part of the standard library in Python 3.5 and later .. class:: ContextDecorator() @@ -426,8 +411,6 @@ statements. If this is not the case, then the original construct with the explicit :keyword:`!with` statement inside the function should be used. - .. versionadded:: 3.2 - .. class:: AsyncContextDecorator @@ -465,7 +448,8 @@ The bit in the middle Finishing - .. versionadded:: 3.10 + .. versionadded:: 21.6.0 + Part of the standard library in Python 3.10 and later .. class:: ExitStack() @@ -504,7 +488,8 @@ foundation for higher level context managers that manipulate the exit stack in application specific ways. - .. versionadded:: 3.3 + .. versionadded:: 0.4 + Part of the standard library in Python 3.3 and later .. method:: enter_context(cm) @@ -580,7 +565,7 @@ The :meth:`close` method is not implemented, :meth:`aclose` must be used instead. - .. coroutinemethod:: enter_async_context(cm) + .. method:: enter_async_context(cm) Similar to :meth:`enter_context` but expects an asynchronous context manager. @@ -594,7 +579,7 @@ Similar to :meth:`callback` but expects a coroutine function. - .. coroutinemethod:: aclose() + .. method:: aclose() Similar to :meth:`close` but properly handles awaitables. @@ -607,7 +592,9 @@ # the async with statement, even if attempts to open a connection # later in the list raise an exception. - .. versionadded:: 3.7 + .. versionadded:: 21.6.0 + Part of the standard library in Python 3.7 and later + Examples and Recipes -------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/dev/py3_10_contextlib_to_contextlib2.patch0000644000175100001710000001230000000000000023455 0ustar00runnerdocker--- ../cpython/Lib/contextlib.py 2021-06-26 16:28:03.835372955 +1000 +++ contextlib2.py 2021-06-26 17:40:30.047079570 +1000 @@ -1,19 +1,32 @@ -"""Utilities for with-statement contexts. See PEP 343.""" +"""contextlib2 - backports and enhancements to the contextlib module""" + import abc import sys +import warnings import _collections_abc from collections import deque from functools import wraps -from types import MethodType, GenericAlias +from types import MethodType + +# Python 3.6/3.7/3.8 compatibility: GenericAlias may not be defined +try: + from types import GenericAlias +except ImportError: + # If the real GenericAlias type doesn't exist, __class_getitem__ won't be used, + # so the fallback placeholder doesn't need to provide any meaningful behaviour + class GenericAlias: + pass + __all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext", "AbstractContextManager", "AbstractAsyncContextManager", "AsyncExitStack", "ContextDecorator", "ExitStack", "redirect_stdout", "redirect_stderr", "suppress", "aclosing"] +# Backwards compatibility +__all__ += ["ContextStack"] class AbstractContextManager(abc.ABC): - """An abstract base class for context managers.""" __class_getitem__ = classmethod(GenericAlias) @@ -60,6 +73,23 @@ class ContextDecorator(object): "A base class or mixin that enables context managers to work as decorators." + def refresh_cm(self): + """Returns the context manager used to actually wrap the call to the + decorated function. + + The default implementation just returns *self*. + + Overriding this method allows otherwise one-shot context managers + like _GeneratorContextManager to support use as decorators via + implicit recreation. + + DEPRECATED: refresh_cm was never added to the standard library's + ContextDecorator API + """ + warnings.warn("refresh_cm was never added to the standard library", + DeprecationWarning) + return self._recreate_cm() + def _recreate_cm(self): """Return a recreated instance of self. @@ -430,7 +460,9 @@ return MethodType(cm_exit, cm) @staticmethod - def _create_cb_wrapper(callback, /, *args, **kwds): + def _create_cb_wrapper(*args, **kwds): + # Python 3.6/3.7 compatibility: no native positional-only args syntax + callback, *args = args def _exit_wrapper(exc_type, exc, tb): callback(*args, **kwds) return _exit_wrapper @@ -479,11 +511,18 @@ self._push_cm_exit(cm, _exit) return result - def callback(self, callback, /, *args, **kwds): + def callback(*args, **kwds): """Registers an arbitrary callback and arguments. Cannot suppress exceptions. """ + # Python 3.6/3.7 compatibility: no native positional-only args syntax + try: + self, callback, *args = args + except ValueError as exc: + exc_details = str(exc).partition("(")[2] + msg = "Not enough positional arguments {}".format(exc_details) + raise TypeError(msg) from None _exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but @@ -589,7 +628,9 @@ return MethodType(cm_exit, cm) @staticmethod - def _create_async_cb_wrapper(callback, /, *args, **kwds): + def _create_async_cb_wrapper(*args, **kwds): + # Python 3.6/3.7 compatibility: no native positional-only args syntax + callback, *args = args async def _exit_wrapper(exc_type, exc, tb): await callback(*args, **kwds) return _exit_wrapper @@ -624,11 +665,18 @@ self._push_async_cm_exit(exit, exit_method) return exit # Allow use as a decorator - def push_async_callback(self, callback, /, *args, **kwds): + def push_async_callback(*args, **kwds): """Registers an arbitrary coroutine function and arguments. Cannot suppress exceptions. """ + # Python 3.6/3.7 compatibility: no native positional-only args syntax + try: + self, callback, *args = args + except ValueError as exc: + exc_details = str(exc).partition("(")[2] + msg = "Not enough positional arguments {}".format(exc_details) + raise TypeError(msg) from None _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but @@ -729,3 +777,22 @@ async def __aexit__(self, *excinfo): pass + + +# Preserve backwards compatibility +class ContextStack(ExitStack): + """Backwards compatibility alias for ExitStack""" + + def __init__(self): + warnings.warn("ContextStack has been renamed to ExitStack", + DeprecationWarning) + super(ContextStack, self).__init__() + + def register_exit(self, callback): + return self.push(callback) + + def register(self, callback, *args, **kwds): + return self.callback(callback, *args, **kwds) + + def preserve(self): + return self.pop_all() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1624775924.9167192 contextlib2-21.6.0/docs/0000755000175100001710000000000000000000000014325 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/docs/Makefile0000644000175100001710000001100200000000000015757 0ustar00runnerdocker# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/contextlib2.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/contextlib2.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/contextlib2" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/contextlib2" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/docs/conf.py0000644000175100001710000001605200000000000015630 0ustar00runnerdocker# -*- coding: utf-8 -*- # # contextlib2 documentation build configuration file, created by # sphinx-quickstart on Tue Dec 13 20:29:56 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('..')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.intersphinx'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'contextlib2' copyright = u'2021, Nick Coghlan' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. with open('../VERSION.txt') as f: version = f.read().strip() # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'contextlib2doc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'contextlib2.tex', u'contextlib2 Documentation', u'Nick Coghlan', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'contextlib2', u'contextlib2 Documentation', [u'Nick Coghlan'], 1) ] # Configuration for intersphinx: refer to the Python 3 standard library. intersphinx_mapping = {'http://docs.python.org/3': None} ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/docs/contextlib2.rst0000644000175100001710000010422100000000000017314 0ustar00runnerdockerAPI Reference ------------- Functions and classes provided: .. class:: AbstractContextManager An :term:`abstract base class` for classes that implement :meth:`object.__enter__` and :meth:`object.__exit__`. A default implementation for :meth:`object.__enter__` is provided which returns ``self`` while :meth:`object.__exit__` is an abstract method which by default returns ``None``. See also the definition of :ref:`typecontextmanager`. .. versionadded:: 0.6.0 Part of the standard library in Python 3.6 and later .. class:: AbstractAsyncContextManager An :term:`abstract base class` for classes that implement :meth:`object.__aenter__` and :meth:`object.__aexit__`. A default implementation for :meth:`object.__aenter__` is provided which returns ``self`` while :meth:`object.__aexit__` is an abstract method which by default returns ``None``. See also the definition of :ref:`async-context-managers`. .. versionadded:: 21.6.0 Part of the standard library in Python 3.7 and later .. decorator:: contextmanager This function is a :term:`decorator` that can be used to define a factory function for :keyword:`with` statement context managers, without needing to create a class or separate :meth:`__enter__` and :meth:`__exit__` methods. While many objects natively support use in with statements, sometimes a resource needs to be managed that isn't a context manager in its own right, and doesn't implement a ``close()`` method for use with ``contextlib.closing`` An abstract example would be the following to ensure correct resource management:: from contextlib import contextmanager @contextmanager def managed_resource(*args, **kwds): # Code to acquire resource, e.g.: resource = acquire_resource(*args, **kwds) try: yield resource finally: # Code to release resource, e.g.: release_resource(resource) >>> with managed_resource(timeout=3600) as resource: ... # Resource is released at the end of this block, ... # even if code in the block raises an exception The function being decorated must return a :term:`generator`-iterator when called. This iterator must yield exactly one value, which will be bound to the targets in the :keyword:`with` statement's :keyword:`!as` clause, if any. At the point where the generator yields, the block nested in the :keyword:`with` statement is executed. The generator is then resumed after the block is exited. If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred. Thus, you can use a :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` statement to trap the error (if any), or ensure that some cleanup takes place. If an exception is trapped merely in order to log it or to perform some action (rather than to suppress it entirely), the generator must reraise that exception. Otherwise the generator context manager will indicate to the :keyword:`!with` statement that the exception has been handled, and execution will resume with the statement immediately following the :keyword:`!with` statement. :func:`contextmanager` uses :class:`ContextDecorator` so the context managers it creates can be used as decorators as well as in :keyword:`with` statements. When used as a decorator, a new generator instance is implicitly created on each function call (this allows the otherwise "one-shot" context managers created by :func:`contextmanager` to meet the requirement that context managers support multiple invocations in order to be used as decorators). .. decorator:: asynccontextmanager Similar to :func:`~contextlib.contextmanager`, but creates an :ref:`asynchronous context manager `. This function is a :term:`decorator` that can be used to define a factory function for :keyword:`async with` statement asynchronous context managers, without needing to create a class or separate :meth:`__aenter__` and :meth:`__aexit__` methods. It must be applied to an :term:`asynchronous generator` function. A simple example:: from contextlib import asynccontextmanager @asynccontextmanager async def get_connection(): conn = await acquire_db_connection() try: yield conn finally: await release_db_connection(conn) async def get_all_users(): async with get_connection() as conn: return conn.query('SELECT ...') .. versionadded:: 21.6.0 Part of the standard library in Python 3.7 and later, enhanced in Python 3.10 and later to allow created async context managers to be used as async function decorators. Context managers defined with :func:`asynccontextmanager` can be used either as decorators or with :keyword:`async with` statements:: import time async def timeit(): now = time.monotonic() try: yield finally: print(f'it took {time.monotonic() - now}s to run') @timeit() async def main(): # ... async code ... When used as a decorator, a new generator instance is implicitly created on each function call. This allows the otherwise "one-shot" context managers created by :func:`asynccontextmanager` to meet the requirement that context managers support multiple invocations in order to be used as decorators. .. function:: closing(thing) Return a context manager that closes *thing* upon completion of the block. This is basically equivalent to:: from contextlib import contextmanager @contextmanager def closing(thing): try: yield thing finally: thing.close() And lets you write code like this:: from contextlib import closing from urllib.request import urlopen with closing(urlopen('http://www.python.org')) as page: for line in page: print(line) without needing to explicitly close ``page``. Even if an error occurs, ``page.close()`` will be called when the :keyword:`with` block is exited. .. class:: aclosing(thing) Return an async context manager that calls the ``aclose()`` method of *thing* upon completion of the block. This is basically equivalent to:: from contextlib import asynccontextmanager @asynccontextmanager async def aclosing(thing): try: yield thing finally: await thing.aclose() Significantly, ``aclosing()`` supports deterministic cleanup of async generators when they happen to exit early by :keyword:`break` or an exception. For example:: from contextlib import aclosing async with aclosing(my_generator()) as values: async for value in values: if value == 42: break This pattern ensures that the generator's async exit code is executed in the same context as its iterations (so that exceptions and context variables work as expected, and the exit code isn't run after the lifetime of some task it depends on). .. versionadded:: 21.6.0 Part of the standard library in Python 3.10 and later .. _simplifying-support-for-single-optional-context-managers: .. function:: nullcontext(enter_result=None) Return a context manager that returns *enter_result* from ``__enter__``, but otherwise does nothing. It is intended to be used as a stand-in for an optional context manager, for example:: def myfunction(arg, ignore_exceptions=False): if ignore_exceptions: # Use suppress to ignore all exceptions. cm = contextlib.suppress(Exception) else: # Do not ignore any exceptions, cm has no effect. cm = contextlib.nullcontext() with cm: # Do something An example using *enter_result*:: def process_file(file_or_path): if isinstance(file_or_path, str): # If string, open file cm = open(file_or_path) else: # Caller is responsible for closing file cm = nullcontext(file_or_path) with cm as file: # Perform processing on the file It can also be used as a stand-in for :ref:`asynchronous context managers `:: async def send_http(session=None): if not session: # If no http session, create it with aiohttp cm = aiohttp.ClientSession() else: # Caller is responsible for closing the session cm = nullcontext(session) async with cm as session: # Send http requests with session .. versionadded:: 0.6.0 Part of the standard library in Python 3.7 and later .. versionchanged:: 21.6.0 Updated to Python 3.10 version with :term:`asynchronous context manager` support .. function:: suppress(*exceptions) Return a context manager that suppresses any of the specified exceptions if they occur in the body of a :keyword:`!with` statement and then resumes execution with the first statement following the end of the :keyword:`!with` statement. As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do. For example:: from contextlib import suppress with suppress(FileNotFoundError): os.remove('somefile.tmp') with suppress(FileNotFoundError): os.remove('someotherfile.tmp') This code is equivalent to:: try: os.remove('somefile.tmp') except FileNotFoundError: pass try: os.remove('someotherfile.tmp') except FileNotFoundError: pass This context manager is :ref:`reentrant `. .. versionadded:: 0.5 Part of the standard library in Python 3.4 and later .. function:: redirect_stdout(new_target) Context manager for temporarily redirecting :data:`sys.stdout` to another file or file-like object. This tool adds flexibility to existing functions or classes whose output is hardwired to stdout. For example, the output of :func:`help` normally is sent to *sys.stdout*. You can capture that output in a string by redirecting the output to an :class:`io.StringIO` object. The replacement stream is returned from the ``__enter__`` method and so is available as the target of the :keyword:`with` statement:: with redirect_stdout(io.StringIO()) as f: help(pow) s = f.getvalue() To send the output of :func:`help` to a file on disk, redirect the output to a regular file:: with open('help.txt', 'w') as f: with redirect_stdout(f): help(pow) To send the output of :func:`help` to *sys.stderr*:: with redirect_stdout(sys.stderr): help(pow) Note that the global side effect on :data:`sys.stdout` means that this context manager is not suitable for use in library code and most threaded applications. It also has no effect on the output of subprocesses. However, it is still a useful approach for many utility scripts. This context manager is :ref:`reentrant `. .. versionadded:: 0.5 Part of the standard library in Python 3.4 and later .. function:: redirect_stderr(new_target) Similar to :func:`~contextlib.redirect_stdout` but redirecting :data:`sys.stderr` to another file or file-like object. This context manager is :ref:`reentrant `. .. versionadded:: 0.5 Part of the standard library in Python 3.5 and later .. class:: ContextDecorator() A base class that enables a context manager to also be used as a decorator. Context managers inheriting from ``ContextDecorator`` have to implement ``__enter__`` and ``__exit__`` as normal. ``__exit__`` retains its optional exception handling even when used as a decorator. ``ContextDecorator`` is used by :func:`contextmanager`, so you get this functionality automatically. Example of ``ContextDecorator``:: from contextlib import ContextDecorator class mycontext(ContextDecorator): def __enter__(self): print('Starting') return self def __exit__(self, *exc): print('Finishing') return False >>> @mycontext() ... def function(): ... print('The bit in the middle') ... >>> function() Starting The bit in the middle Finishing >>> with mycontext(): ... print('The bit in the middle') ... Starting The bit in the middle Finishing This change is just syntactic sugar for any construct of the following form:: def f(): with cm(): # Do stuff ``ContextDecorator`` lets you instead write:: @cm() def f(): # Do stuff It makes it clear that the ``cm`` applies to the whole function, rather than just a piece of it (and saving an indentation level is nice, too). Existing context managers that already have a base class can be extended by using ``ContextDecorator`` as a mixin class:: from contextlib import ContextDecorator class mycontext(ContextBaseClass, ContextDecorator): def __enter__(self): return self def __exit__(self, *exc): return False .. note:: As the decorated function must be able to be called multiple times, the underlying context manager must support use in multiple :keyword:`with` statements. If this is not the case, then the original construct with the explicit :keyword:`!with` statement inside the function should be used. .. class:: AsyncContextDecorator Similar to :class:`ContextDecorator` but only for asynchronous functions. Example of ``AsyncContextDecorator``:: from asyncio import run from contextlib import AsyncContextDecorator class mycontext(AsyncContextDecorator): async def __aenter__(self): print('Starting') return self async def __aexit__(self, *exc): print('Finishing') return False >>> @mycontext() ... async def function(): ... print('The bit in the middle') ... >>> run(function()) Starting The bit in the middle Finishing >>> async def function(): ... async with mycontext(): ... print('The bit in the middle') ... >>> run(function()) Starting The bit in the middle Finishing .. versionadded:: 21.6.0 Part of the standard library in Python 3.10 and later .. class:: ExitStack() A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those that are optional or otherwise driven by input data. For example, a set of files may easily be handled in a single with statement as follows:: with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in filenames] # All opened files will automatically be closed at the end of # the with statement, even if attempts to open files later # in the list raise an exception Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed (either explicitly or implicitly at the end of a :keyword:`with` statement). Note that callbacks are *not* invoked implicitly when the context stack instance is garbage collected. This stack model is used so that context managers that acquire their resources in their ``__init__`` method (such as file objects) can be handled correctly. Since registered callbacks are invoked in the reverse order of registration, this ends up behaving as if multiple nested :keyword:`with` statements had been used with the registered set of callbacks. This even extends to exception handling - if an inner callback suppresses or replaces an exception, then outer callbacks will be passed arguments based on that updated state. This is a relatively low level API that takes care of the details of correctly unwinding the stack of exit callbacks. It provides a suitable foundation for higher level context managers that manipulate the exit stack in application specific ways. .. versionadded:: 0.4 Part of the standard library in Python 3.3 and later .. method:: enter_context(cm) Enters a new context manager and adds its :meth:`__exit__` method to the callback stack. The return value is the result of the context manager's own :meth:`__enter__` method. These context managers may suppress exceptions just as they normally would if used directly as part of a :keyword:`with` statement. .. method:: push(exit) Adds a context manager's :meth:`__exit__` method to the callback stack. As ``__enter__`` is *not* invoked, this method can be used to cover part of an :meth:`__enter__` implementation with a context manager's own :meth:`__exit__` method. If passed an object that is not a context manager, this method assumes it is a callback with the same signature as a context manager's :meth:`__exit__` method and adds it directly to the callback stack. By returning true values, these callbacks can suppress exceptions the same way context manager :meth:`__exit__` methods can. The passed in object is returned from the function, allowing this method to be used as a function decorator. .. method:: callback(callback, /, *args, **kwds) Accepts an arbitrary callback function and arguments and adds it to the callback stack. Unlike the other methods, callbacks added this way cannot suppress exceptions (as they are never passed the exception details). The passed in callback is returned from the function, allowing this method to be used as a function decorator. .. method:: pop_all() Transfers the callback stack to a fresh :class:`ExitStack` instance and returns it. No callbacks are invoked by this operation - instead, they will now be invoked when the new stack is closed (either explicitly or implicitly at the end of a :keyword:`with` statement). For example, a group of files can be opened as an "all or nothing" operation as follows:: with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in filenames] # Hold onto the close method, but don't call it yet. close_files = stack.pop_all().close # If opening any file fails, all previously opened files will be # closed automatically. If all files are opened successfully, # they will remain open even after the with statement ends. # close_files() can then be invoked explicitly to close them all. .. method:: close() Immediately unwinds the callback stack, invoking callbacks in the reverse order of registration. For any context managers and exit callbacks registered, the arguments passed in will indicate that no exception occurred. .. class:: AsyncExitStack() An :ref:`asynchronous context manager `, similar to :class:`ExitStack`, that supports combining both synchronous and asynchronous context managers, as well as having coroutines for cleanup logic. The :meth:`close` method is not implemented, :meth:`aclose` must be used instead. .. method:: enter_async_context(cm) Similar to :meth:`enter_context` but expects an asynchronous context manager. .. method:: push_async_exit(exit) Similar to :meth:`push` but expects either an asynchronous context manager or a coroutine function. .. method:: push_async_callback(callback, /, *args, **kwds) Similar to :meth:`callback` but expects a coroutine function. .. method:: aclose() Similar to :meth:`close` but properly handles awaitables. Continuing the example for :func:`asynccontextmanager`:: async with AsyncExitStack() as stack: connections = [await stack.enter_async_context(get_connection()) for i in range(5)] # All opened connections will automatically be released at the end of # the async with statement, even if attempts to open a connection # later in the list raise an exception. .. versionadded:: 21.6.0 Part of the standard library in Python 3.7 and later Examples and Recipes -------------------- This section describes some examples and recipes for making effective use of the tools provided by :mod:`contextlib`. Supporting a variable number of context managers ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The primary use case for :class:`ExitStack` is the one given in the class documentation: supporting a variable number of context managers and other cleanup operations in a single :keyword:`with` statement. The variability may come from the number of context managers needed being driven by user input (such as opening a user specified collection of files), or from some of the context managers being optional:: with ExitStack() as stack: for resource in resources: stack.enter_context(resource) if need_special_resource(): special = acquire_special_resource() stack.callback(release_special_resource, special) # Perform operations that use the acquired resources As shown, :class:`ExitStack` also makes it quite easy to use :keyword:`with` statements to manage arbitrary resources that don't natively support the context management protocol. Catching exceptions from ``__enter__`` methods ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ It is occasionally desirable to catch exceptions from an ``__enter__`` method implementation, *without* inadvertently catching exceptions from the :keyword:`with` statement body or the context manager's ``__exit__`` method. By using :class:`ExitStack` the steps in the context management protocol can be separated slightly in order to allow this:: stack = ExitStack() try: x = stack.enter_context(cm) except Exception: # handle __enter__ exception else: with stack: # Handle normal case Actually needing to do this is likely to indicate that the underlying API should be providing a direct resource management interface for use with :keyword:`try`/:keyword:`except`/:keyword:`finally` statements, but not all APIs are well designed in that regard. When a context manager is the only resource management API provided, then :class:`ExitStack` can make it easier to handle various situations that can't be handled directly in a :keyword:`with` statement. Cleaning up in an ``__enter__`` implementation ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ As noted in the documentation of :meth:`ExitStack.push`, this method can be useful in cleaning up an already allocated resource if later steps in the :meth:`__enter__` implementation fail. Here's an example of doing this for a context manager that accepts resource acquisition and release functions, along with an optional validation function, and maps them to the context management protocol:: from contextlib import contextmanager, AbstractContextManager, ExitStack class ResourceManager(AbstractContextManager): def __init__(self, acquire_resource, release_resource, check_resource_ok=None): self.acquire_resource = acquire_resource self.release_resource = release_resource if check_resource_ok is None: def check_resource_ok(resource): return True self.check_resource_ok = check_resource_ok @contextmanager def _cleanup_on_error(self): with ExitStack() as stack: stack.push(self) yield # The validation check passed and didn't raise an exception # Accordingly, we want to keep the resource, and pass it # back to our caller stack.pop_all() def __enter__(self): resource = self.acquire_resource() with self._cleanup_on_error(): if not self.check_resource_ok(resource): msg = "Failed validation for {!r}" raise RuntimeError(msg.format(resource)) return resource def __exit__(self, *exc_details): # We don't need to duplicate any of our resource release logic self.release_resource() Replacing any use of ``try-finally`` and flag variables ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A pattern you will sometimes see is a ``try-finally`` statement with a flag variable to indicate whether or not the body of the ``finally`` clause should be executed. In its simplest form (that can't already be handled just by using an ``except`` clause instead), it looks something like this:: cleanup_needed = True try: result = perform_operation() if result: cleanup_needed = False finally: if cleanup_needed: cleanup_resources() As with any ``try`` statement based code, this can cause problems for development and review, because the setup code and the cleanup code can end up being separated by arbitrarily long sections of code. :class:`ExitStack` makes it possible to instead register a callback for execution at the end of a ``with`` statement, and then later decide to skip executing that callback:: from contextlib import ExitStack with ExitStack() as stack: stack.callback(cleanup_resources) result = perform_operation() if result: stack.pop_all() This allows the intended cleanup up behaviour to be made explicit up front, rather than requiring a separate flag variable. If a particular application uses this pattern a lot, it can be simplified even further by means of a small helper class:: from contextlib import ExitStack class Callback(ExitStack): def __init__(self, callback, /, *args, **kwds): super().__init__() self.callback(callback, *args, **kwds) def cancel(self): self.pop_all() with Callback(cleanup_resources) as cb: result = perform_operation() if result: cb.cancel() If the resource cleanup isn't already neatly bundled into a standalone function, then it is still possible to use the decorator form of :meth:`ExitStack.callback` to declare the resource cleanup in advance:: from contextlib import ExitStack with ExitStack() as stack: @stack.callback def cleanup_resources(): ... result = perform_operation() if result: stack.pop_all() Due to the way the decorator protocol works, a callback function declared this way cannot take any parameters. Instead, any resources to be released must be accessed as closure variables. Using a context manager as a function decorator ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :class:`ContextDecorator` makes it possible to use a context manager in both an ordinary ``with`` statement and also as a function decorator. For example, it is sometimes useful to wrap functions or groups of statements with a logger that can track the time of entry and time of exit. Rather than writing both a function decorator and a context manager for the task, inheriting from :class:`ContextDecorator` provides both capabilities in a single definition:: from contextlib import ContextDecorator import logging logging.basicConfig(level=logging.INFO) class track_entry_and_exit(ContextDecorator): def __init__(self, name): self.name = name def __enter__(self): logging.info('Entering: %s', self.name) def __exit__(self, exc_type, exc, exc_tb): logging.info('Exiting: %s', self.name) Instances of this class can be used as both a context manager:: with track_entry_and_exit('widget loader'): print('Some time consuming activity goes here') load_widget() And also as a function decorator:: @track_entry_and_exit('widget loader') def activity(): print('Some time consuming activity goes here') load_widget() Note that there is one additional limitation when using context managers as function decorators: there's no way to access the return value of :meth:`__enter__`. If that value is needed, then it is still necessary to use an explicit ``with`` statement. .. seealso:: :pep:`343` - The "with" statement The specification, background, and examples for the Python :keyword:`with` statement. .. _single-use-reusable-and-reentrant-cms: Single use, reusable and reentrant context managers --------------------------------------------------- Most context managers are written in a way that means they can only be used effectively in a :keyword:`with` statement once. These single use context managers must be created afresh each time they're used - attempting to use them a second time will trigger an exception or otherwise not work correctly. This common limitation means that it is generally advisable to create context managers directly in the header of the :keyword:`with` statement where they are used (as shown in all of the usage examples above). Files are an example of effectively single use context managers, since the first :keyword:`with` statement will close the file, preventing any further IO operations using that file object. Context managers created using :func:`contextmanager` are also single use context managers, and will complain about the underlying generator failing to yield if an attempt is made to use them a second time:: >>> from contextlib import contextmanager >>> @contextmanager ... def singleuse(): ... print("Before") ... yield ... print("After") ... >>> cm = singleuse() >>> with cm: ... pass ... Before After >>> with cm: ... pass ... Traceback (most recent call last): ... RuntimeError: generator didn't yield .. _reentrant-cms: Reentrant context managers ^^^^^^^^^^^^^^^^^^^^^^^^^^ More sophisticated context managers may be "reentrant". These context managers can not only be used in multiple :keyword:`with` statements, but may also be used *inside* a :keyword:`!with` statement that is already using the same context manager. :class:`threading.RLock` is an example of a reentrant context manager, as are :func:`suppress` and :func:`redirect_stdout`. Here's a very simple example of reentrant use:: >>> from contextlib import redirect_stdout >>> from io import StringIO >>> stream = StringIO() >>> write_to_stream = redirect_stdout(stream) >>> with write_to_stream: ... print("This is written to the stream rather than stdout") ... with write_to_stream: ... print("This is also written to the stream") ... >>> print("This is written directly to stdout") This is written directly to stdout >>> print(stream.getvalue()) This is written to the stream rather than stdout This is also written to the stream Real world examples of reentrancy are more likely to involve multiple functions calling each other and hence be far more complicated than this example. Note also that being reentrant is *not* the same thing as being thread safe. :func:`redirect_stdout`, for example, is definitely not thread safe, as it makes a global modification to the system state by binding :data:`sys.stdout` to a different stream. .. _reusable-cms: Reusable context managers ^^^^^^^^^^^^^^^^^^^^^^^^^ Distinct from both single use and reentrant context managers are "reusable" context managers (or, to be completely explicit, "reusable, but not reentrant" context managers, since reentrant context managers are also reusable). These context managers support being used multiple times, but will fail (or otherwise not work correctly) if the specific context manager instance has already been used in a containing with statement. :class:`threading.Lock` is an example of a reusable, but not reentrant, context manager (for a reentrant lock, it is necessary to use :class:`threading.RLock` instead). Another example of a reusable, but not reentrant, context manager is :class:`ExitStack`, as it invokes *all* currently registered callbacks when leaving any with statement, regardless of where those callbacks were added:: >>> from contextlib import ExitStack >>> stack = ExitStack() >>> with stack: ... stack.callback(print, "Callback: from first context") ... print("Leaving first context") ... Leaving first context Callback: from first context >>> with stack: ... stack.callback(print, "Callback: from second context") ... print("Leaving second context") ... Leaving second context Callback: from second context >>> with stack: ... stack.callback(print, "Callback: from outer context") ... with stack: ... stack.callback(print, "Callback: from inner context") ... print("Leaving inner context") ... print("Leaving outer context") ... Leaving inner context Callback: from inner context Callback: from outer context Leaving outer context As the output from the example shows, reusing a single stack object across multiple with statements works correctly, but attempting to nest them will cause the stack to be cleared at the end of the innermost with statement, which is unlikely to be desirable behaviour. Using separate :class:`ExitStack` instances instead of reusing a single instance avoids that problem:: >>> from contextlib import ExitStack >>> with ExitStack() as outer_stack: ... outer_stack.callback(print, "Callback: from outer context") ... with ExitStack() as inner_stack: ... inner_stack.callback(print, "Callback: from inner context") ... print("Leaving inner context") ... print("Leaving outer context") ... Leaving inner context Callback: from inner context Leaving outer context Callback: from outer context ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/docs/index.rst0000644000175100001710000000520100000000000016164 0ustar00runnerdocker.. contextlib2 documentation master file, created by sphinx-quickstart on Tue Dec 13 20:29:56 2011. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. contextlib2 --- Updated utilities for context management ======================================================== .. module:: contextlib2 :synopsis: Backports and future enhancements for the contextlib module This module provides backports of features in the latest version of the standard library's :mod:`contextlib` module to earlier Python versions. It also serves as a real world proving ground for potential future enhancements to that module. Like :mod:`contextlib`, this module provides utilities for common tasks involving the ``with`` and ``async with`` statements. Additions Relative to the Standard Library ------------------------------------------ This module is primarily a backport of the Python 3.10 version of :mod:`contextlib` to earlier releases. The async context management features require asynchronous generator support in the language runtime, so the oldest supported version is now Python 3.6 (contextlib2 0.6.0 and earlier support older Python versions by omitting all asynchronous features). This module is also a proving ground for new features not yet part of the standard library. There are currently no such features in the module. Finally, this module contains some deprecated APIs which never graduated to standard library inclusion. These interfaces are no longer documented, but may still be present in the code (emitting ``DeprecationWarning`` if used). Using the Module ==================== .. toctree:: contextlib2.rst Obtaining the Module ==================== This module can be installed directly from the `Python Package Index`_ with pip_:: pip install contextlib2 Alternatively, you can download and unpack it manually from the `contextlib2 PyPI page`_. There are no operating system or distribution specific versions of this module - it is a pure Python module that should work on all platforms. Supported Python versions are currently 3.6+. .. _Python Package Index: http://pypi.python.org .. _pip: http://www.pip-installer.org .. _contextlib2 pypi page: http://pypi.python.org/pypi/contextlib2 Development and Support ----------------------- contextlib2 is developed and maintained on GitHub_. Problems and suggested improvements can be posted to the `issue tracker`_. .. _GitHub: https://github.com/jazzband/contextlib2 .. _issue tracker: https://github.com/jazzband/contextlib2/issues .. include:: ../NEWS.rst Indices and tables ================== * :ref:`genindex` * :ref:`search` ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/docs/make.bat0000644000175100001710000001065100000000000015735 0ustar00runnerdocker@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\contextlib2.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\contextlib2.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1624775924.9167192 contextlib2-21.6.0/setup.cfg0000644000175100001710000000010300000000000015210 0ustar00runnerdocker[bdist_wheel] universal = 1 [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/setup.py0000755000175100001710000000226300000000000015115 0ustar00runnerdocker#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='contextlib2', version=open('VERSION.txt').read().strip(), python_requires='>=3.6', packages=['contextlib2'], include_package_data=True, license='PSF License', description='Backports and enhancements for the contextlib module', long_description=open('README.rst').read(), author='Nick Coghlan', author_email='ncoghlan@gmail.com', url='http://contextlib2.readthedocs.org', classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'License :: OSI Approved :: Python Software Foundation License', # These are the Python versions tested, it may work on others # It definitely won't work on versions without native async support 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', ], ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1624775924.9167192 contextlib2-21.6.0/test/0000755000175100001710000000000000000000000014354 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/test/__init__.py0000644000175100001710000000011500000000000016462 0ustar00runnerdocker# unittest test discovery requires an __init__.py file in the test directory ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1624775924.9167192 contextlib2-21.6.0/test/support/0000755000175100001710000000000000000000000016070 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/test/support/__init__.py0000644000175100001710000000034400000000000020202 0ustar00runnerdocker"""Enough of the test.support APIs to run the contextlib test suite""" import sys import unittest requires_docstrings = unittest.skipIf(sys.flags.optimize >= 2, "Test requires docstrings") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/test/support/os_helper.py0000644000175100001710000000015700000000000020425 0ustar00runnerdocker"""Enough of the test.support.os_helper APIs to run the contextlib test suite""" import os unlink = os.unlink ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/test/test_contextlib.py0000644000175100001710000010132500000000000020142 0ustar00runnerdocker"""Unit tests for contextlib.py, and other context managers.""" import io import sys import tempfile import threading import unittest from contextlib2 import * # Tests __all__ from test import support from test.support import os_helper import weakref import gc class TestAbstractContextManager(unittest.TestCase): def test_enter(self): class DefaultEnter(AbstractContextManager): def __exit__(self, *args): super().__exit__(*args) manager = DefaultEnter() self.assertIs(manager.__enter__(), manager) def test_exit_is_abstract(self): class MissingExit(AbstractContextManager): pass with self.assertRaises(TypeError): MissingExit() def test_structural_subclassing(self): class ManagerFromScratch: def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): return None self.assertTrue(issubclass(ManagerFromScratch, AbstractContextManager)) class DefaultEnter(AbstractContextManager): def __exit__(self, *args): super().__exit__(*args) self.assertTrue(issubclass(DefaultEnter, AbstractContextManager)) class NoEnter(ManagerFromScratch): __enter__ = None self.assertFalse(issubclass(NoEnter, AbstractContextManager)) class NoExit(ManagerFromScratch): __exit__ = None self.assertFalse(issubclass(NoExit, AbstractContextManager)) class ContextManagerTestCase(unittest.TestCase): def test_contextmanager_plain(self): state = [] @contextmanager def woohoo(): state.append(1) yield 42 state.append(999) with woohoo() as x: self.assertEqual(state, [1]) self.assertEqual(x, 42) state.append(x) self.assertEqual(state, [1, 42, 999]) def test_contextmanager_finally(self): state = [] @contextmanager def woohoo(): state.append(1) try: yield 42 finally: state.append(999) with self.assertRaises(ZeroDivisionError): with woohoo() as x: self.assertEqual(state, [1]) self.assertEqual(x, 42) state.append(x) raise ZeroDivisionError() self.assertEqual(state, [1, 42, 999]) def test_contextmanager_no_reraise(self): @contextmanager def whee(): yield ctx = whee() ctx.__enter__() # Calling __exit__ should not result in an exception self.assertFalse(ctx.__exit__(TypeError, TypeError("foo"), None)) def test_contextmanager_trap_yield_after_throw(self): @contextmanager def whoo(): try: yield except: yield ctx = whoo() ctx.__enter__() self.assertRaises( RuntimeError, ctx.__exit__, TypeError, TypeError("foo"), None ) def test_contextmanager_except(self): state = [] @contextmanager def woohoo(): state.append(1) try: yield 42 except ZeroDivisionError as e: state.append(e.args[0]) self.assertEqual(state, [1, 42, 999]) with woohoo() as x: self.assertEqual(state, [1]) self.assertEqual(x, 42) state.append(x) raise ZeroDivisionError(999) self.assertEqual(state, [1, 42, 999]) def test_contextmanager_except_stopiter(self): stop_exc = StopIteration('spam') @contextmanager def woohoo(): yield try: with self.assertWarnsRegex(DeprecationWarning, "StopIteration"): with woohoo(): raise stop_exc except Exception as ex: self.assertIs(ex, stop_exc) else: self.fail('StopIteration was suppressed') def test_contextmanager_except_pep479(self): code = """\ from __future__ import generator_stop from contextlib import contextmanager @contextmanager def woohoo(): yield """ locals = {} exec(code, locals, locals) woohoo = locals['woohoo'] stop_exc = StopIteration('spam') try: with woohoo(): raise stop_exc except Exception as ex: self.assertIs(ex, stop_exc) else: self.fail('StopIteration was suppressed') def test_contextmanager_do_not_unchain_non_stopiteration_exceptions(self): @contextmanager def test_issue29692(): try: yield except Exception as exc: raise RuntimeError('issue29692:Chained') from exc try: with test_issue29692(): raise ZeroDivisionError except Exception as ex: self.assertIs(type(ex), RuntimeError) self.assertEqual(ex.args[0], 'issue29692:Chained') self.assertIsInstance(ex.__cause__, ZeroDivisionError) try: with test_issue29692(): raise StopIteration('issue29692:Unchained') except Exception as ex: self.assertIs(type(ex), StopIteration) self.assertEqual(ex.args[0], 'issue29692:Unchained') self.assertIsNone(ex.__cause__) def _create_contextmanager_attribs(self): def attribs(**kw): def decorate(func): for k,v in kw.items(): setattr(func,k,v) return func return decorate @contextmanager @attribs(foo='bar') def baz(spam): """Whee!""" return baz def test_contextmanager_attribs(self): baz = self._create_contextmanager_attribs() self.assertEqual(baz.__name__,'baz') self.assertEqual(baz.foo, 'bar') @support.requires_docstrings def test_contextmanager_doc_attrib(self): baz = self._create_contextmanager_attribs() self.assertEqual(baz.__doc__, "Whee!") @support.requires_docstrings def test_instance_docstring_given_cm_docstring(self): baz = self._create_contextmanager_attribs()(None) self.assertEqual(baz.__doc__, "Whee!") def test_keywords(self): # Ensure no keyword arguments are inhibited @contextmanager def woohoo(self, func, args, kwds): yield (self, func, args, kwds) with woohoo(self=11, func=22, args=33, kwds=44) as target: self.assertEqual(target, (11, 22, 33, 44)) def test_nokeepref(self): class A: pass @contextmanager def woohoo(a, b): a = weakref.ref(a) b = weakref.ref(b) # Allow test to work with a non-refcounted GC gc.collect(); gc.collect(); gc.collect() self.assertIsNone(a()) self.assertIsNone(b()) yield with woohoo(A(), b=A()): pass def test_param_errors(self): @contextmanager def woohoo(a, *, b): yield with self.assertRaises(TypeError): woohoo() with self.assertRaises(TypeError): woohoo(3, 5) with self.assertRaises(TypeError): woohoo(b=3) def test_recursive(self): depth = 0 @contextmanager def woohoo(): nonlocal depth before = depth depth += 1 yield depth -= 1 self.assertEqual(depth, before) @woohoo() def recursive(): if depth < 10: recursive() recursive() self.assertEqual(depth, 0) class ClosingTestCase(unittest.TestCase): @support.requires_docstrings def test_instance_docs(self): # Issue 19330: ensure context manager instances have good docstrings cm_docstring = closing.__doc__ obj = closing(None) self.assertEqual(obj.__doc__, cm_docstring) def test_closing(self): state = [] class C: def close(self): state.append(1) x = C() self.assertEqual(state, []) with closing(x) as y: self.assertEqual(x, y) self.assertEqual(state, [1]) def test_closing_error(self): state = [] class C: def close(self): state.append(1) x = C() self.assertEqual(state, []) with self.assertRaises(ZeroDivisionError): with closing(x) as y: self.assertEqual(x, y) 1 / 0 self.assertEqual(state, [1]) class NullcontextTestCase(unittest.TestCase): def test_nullcontext(self): class C: pass c = C() with nullcontext(c) as c_in: self.assertIs(c_in, c) class FileContextTestCase(unittest.TestCase): def testWithOpen(self): tfn = tempfile.mktemp() try: f = None with open(tfn, "w", encoding="utf-8") as f: self.assertFalse(f.closed) f.write("Booh\n") self.assertTrue(f.closed) f = None with self.assertRaises(ZeroDivisionError): with open(tfn, "r", encoding="utf-8") as f: self.assertFalse(f.closed) self.assertEqual(f.read(), "Booh\n") 1 / 0 self.assertTrue(f.closed) finally: os_helper.unlink(tfn) class LockContextTestCase(unittest.TestCase): def boilerPlate(self, lock, locked): self.assertFalse(locked()) with lock: self.assertTrue(locked()) self.assertFalse(locked()) with self.assertRaises(ZeroDivisionError): with lock: self.assertTrue(locked()) 1 / 0 self.assertFalse(locked()) def testWithLock(self): lock = threading.Lock() self.boilerPlate(lock, lock.locked) def testWithRLock(self): lock = threading.RLock() self.boilerPlate(lock, lock._is_owned) def testWithCondition(self): lock = threading.Condition() def locked(): return lock._is_owned() self.boilerPlate(lock, locked) def testWithSemaphore(self): lock = threading.Semaphore() def locked(): if lock.acquire(False): lock.release() return False else: return True self.boilerPlate(lock, locked) def testWithBoundedSemaphore(self): lock = threading.BoundedSemaphore() def locked(): if lock.acquire(False): lock.release() return False else: return True self.boilerPlate(lock, locked) class mycontext(ContextDecorator): """Example decoration-compatible context manager for testing""" started = False exc = None catch = False def __enter__(self): self.started = True return self def __exit__(self, *exc): self.exc = exc return self.catch class TestContextDecorator(unittest.TestCase): @support.requires_docstrings def test_instance_docs(self): # Issue 19330: ensure context manager instances have good docstrings cm_docstring = mycontext.__doc__ obj = mycontext() self.assertEqual(obj.__doc__, cm_docstring) def test_contextdecorator(self): context = mycontext() with context as result: self.assertIs(result, context) self.assertTrue(context.started) self.assertEqual(context.exc, (None, None, None)) def test_contextdecorator_with_exception(self): context = mycontext() with self.assertRaisesRegex(NameError, 'foo'): with context: raise NameError('foo') self.assertIsNotNone(context.exc) self.assertIs(context.exc[0], NameError) context = mycontext() context.catch = True with context: raise NameError('foo') self.assertIsNotNone(context.exc) self.assertIs(context.exc[0], NameError) def test_decorator(self): context = mycontext() @context def test(): self.assertIsNone(context.exc) self.assertTrue(context.started) test() self.assertEqual(context.exc, (None, None, None)) def test_decorator_with_exception(self): context = mycontext() @context def test(): self.assertIsNone(context.exc) self.assertTrue(context.started) raise NameError('foo') with self.assertRaisesRegex(NameError, 'foo'): test() self.assertIsNotNone(context.exc) self.assertIs(context.exc[0], NameError) def test_decorating_method(self): context = mycontext() class Test(object): @context def method(self, a, b, c=None): self.a = a self.b = b self.c = c # these tests are for argument passing when used as a decorator test = Test() test.method(1, 2) self.assertEqual(test.a, 1) self.assertEqual(test.b, 2) self.assertEqual(test.c, None) test = Test() test.method('a', 'b', 'c') self.assertEqual(test.a, 'a') self.assertEqual(test.b, 'b') self.assertEqual(test.c, 'c') test = Test() test.method(a=1, b=2) self.assertEqual(test.a, 1) self.assertEqual(test.b, 2) def test_typo_enter(self): class mycontext(ContextDecorator): def __unter__(self): pass def __exit__(self, *exc): pass with self.assertRaises(AttributeError): with mycontext(): pass def test_typo_exit(self): class mycontext(ContextDecorator): def __enter__(self): pass def __uxit__(self, *exc): pass with self.assertRaises(AttributeError): with mycontext(): pass def test_contextdecorator_as_mixin(self): class somecontext(object): started = False exc = None def __enter__(self): self.started = True return self def __exit__(self, *exc): self.exc = exc class mycontext(somecontext, ContextDecorator): pass context = mycontext() @context def test(): self.assertIsNone(context.exc) self.assertTrue(context.started) test() self.assertEqual(context.exc, (None, None, None)) def test_contextmanager_as_decorator(self): @contextmanager def woohoo(y): state.append(y) yield state.append(999) state = [] @woohoo(1) def test(x): self.assertEqual(state, [1]) state.append(x) test('something') self.assertEqual(state, [1, 'something', 999]) # Issue #11647: Ensure the decorated function is 'reusable' state = [] test('something else') self.assertEqual(state, [1, 'something else', 999]) class TestBaseExitStack: exit_stack = None @support.requires_docstrings def test_instance_docs(self): # Issue 19330: ensure context manager instances have good docstrings cm_docstring = self.exit_stack.__doc__ obj = self.exit_stack() self.assertEqual(obj.__doc__, cm_docstring) def test_no_resources(self): with self.exit_stack(): pass def test_callback(self): expected = [ ((), {}), ((1,), {}), ((1,2), {}), ((), dict(example=1)), ((1,), dict(example=1)), ((1,2), dict(example=1)), ((1,2), dict(self=3, callback=4)), ] result = [] def _exit(*args, **kwds): """Test metadata propagation""" result.append((args, kwds)) with self.exit_stack() as stack: for args, kwds in reversed(expected): if args and kwds: f = stack.callback(_exit, *args, **kwds) elif args: f = stack.callback(_exit, *args) elif kwds: f = stack.callback(_exit, **kwds) else: f = stack.callback(_exit) self.assertIs(f, _exit) for wrapper in stack._exit_callbacks: self.assertIs(wrapper[1].__wrapped__, _exit) self.assertNotEqual(wrapper[1].__name__, _exit.__name__) self.assertIsNone(wrapper[1].__doc__, _exit.__doc__) self.assertEqual(result, expected) result = [] with self.exit_stack() as stack: with self.assertRaises(TypeError): stack.callback(arg=1) with self.assertRaises(TypeError): self.exit_stack.callback(arg=2) with self.assertRaises(TypeError): stack.callback(callback=_exit, arg=3) self.assertEqual(result, []) def test_push(self): exc_raised = ZeroDivisionError def _expect_exc(exc_type, exc, exc_tb): self.assertIs(exc_type, exc_raised) def _suppress_exc(*exc_details): return True def _expect_ok(exc_type, exc, exc_tb): self.assertIsNone(exc_type) self.assertIsNone(exc) self.assertIsNone(exc_tb) class ExitCM(object): def __init__(self, check_exc): self.check_exc = check_exc def __enter__(self): self.fail("Should not be called!") def __exit__(self, *exc_details): self.check_exc(*exc_details) with self.exit_stack() as stack: stack.push(_expect_ok) self.assertIs(stack._exit_callbacks[-1][1], _expect_ok) cm = ExitCM(_expect_ok) stack.push(cm) self.assertIs(stack._exit_callbacks[-1][1].__self__, cm) stack.push(_suppress_exc) self.assertIs(stack._exit_callbacks[-1][1], _suppress_exc) cm = ExitCM(_expect_exc) stack.push(cm) self.assertIs(stack._exit_callbacks[-1][1].__self__, cm) stack.push(_expect_exc) self.assertIs(stack._exit_callbacks[-1][1], _expect_exc) stack.push(_expect_exc) self.assertIs(stack._exit_callbacks[-1][1], _expect_exc) 1/0 def test_enter_context(self): class TestCM(object): def __enter__(self): result.append(1) def __exit__(self, *exc_details): result.append(3) result = [] cm = TestCM() with self.exit_stack() as stack: @stack.callback # Registered first => cleaned up last def _exit(): result.append(4) self.assertIsNotNone(_exit) stack.enter_context(cm) self.assertIs(stack._exit_callbacks[-1][1].__self__, cm) result.append(2) self.assertEqual(result, [1, 2, 3, 4]) def test_close(self): result = [] with self.exit_stack() as stack: @stack.callback def _exit(): result.append(1) self.assertIsNotNone(_exit) stack.close() result.append(2) self.assertEqual(result, [1, 2]) def test_pop_all(self): result = [] with self.exit_stack() as stack: @stack.callback def _exit(): result.append(3) self.assertIsNotNone(_exit) new_stack = stack.pop_all() result.append(1) result.append(2) new_stack.close() self.assertEqual(result, [1, 2, 3]) def test_exit_raise(self): with self.assertRaises(ZeroDivisionError): with self.exit_stack() as stack: stack.push(lambda *exc: False) 1/0 def test_exit_suppress(self): with self.exit_stack() as stack: stack.push(lambda *exc: True) 1/0 def test_exit_exception_chaining_reference(self): # Sanity check to make sure that ExitStack chaining matches # actual nested with statements class RaiseExc: def __init__(self, exc): self.exc = exc def __enter__(self): return self def __exit__(self, *exc_details): raise self.exc class RaiseExcWithContext: def __init__(self, outer, inner): self.outer = outer self.inner = inner def __enter__(self): return self def __exit__(self, *exc_details): try: raise self.inner except: raise self.outer class SuppressExc: def __enter__(self): return self def __exit__(self, *exc_details): type(self).saved_details = exc_details return True try: with RaiseExc(IndexError): with RaiseExcWithContext(KeyError, AttributeError): with SuppressExc(): with RaiseExc(ValueError): 1 / 0 except IndexError as exc: self.assertIsInstance(exc.__context__, KeyError) self.assertIsInstance(exc.__context__.__context__, AttributeError) # Inner exceptions were suppressed self.assertIsNone(exc.__context__.__context__.__context__) else: self.fail("Expected IndexError, but no exception was raised") # Check the inner exceptions inner_exc = SuppressExc.saved_details[1] self.assertIsInstance(inner_exc, ValueError) self.assertIsInstance(inner_exc.__context__, ZeroDivisionError) def test_exit_exception_chaining(self): # Ensure exception chaining matches the reference behaviour def raise_exc(exc): raise exc saved_details = None def suppress_exc(*exc_details): nonlocal saved_details saved_details = exc_details return True try: with self.exit_stack() as stack: stack.callback(raise_exc, IndexError) stack.callback(raise_exc, KeyError) stack.callback(raise_exc, AttributeError) stack.push(suppress_exc) stack.callback(raise_exc, ValueError) 1 / 0 except IndexError as exc: self.assertIsInstance(exc.__context__, KeyError) self.assertIsInstance(exc.__context__.__context__, AttributeError) # Inner exceptions were suppressed self.assertIsNone(exc.__context__.__context__.__context__) else: self.fail("Expected IndexError, but no exception was raised") # Check the inner exceptions inner_exc = saved_details[1] self.assertIsInstance(inner_exc, ValueError) self.assertIsInstance(inner_exc.__context__, ZeroDivisionError) def test_exit_exception_non_suppressing(self): # http://bugs.python.org/issue19092 def raise_exc(exc): raise exc def suppress_exc(*exc_details): return True try: with self.exit_stack() as stack: stack.callback(lambda: None) stack.callback(raise_exc, IndexError) except Exception as exc: self.assertIsInstance(exc, IndexError) else: self.fail("Expected IndexError, but no exception was raised") try: with self.exit_stack() as stack: stack.callback(raise_exc, KeyError) stack.push(suppress_exc) stack.callback(raise_exc, IndexError) except Exception as exc: self.assertIsInstance(exc, KeyError) else: self.fail("Expected KeyError, but no exception was raised") def test_exit_exception_with_correct_context(self): # http://bugs.python.org/issue20317 @contextmanager def gets_the_context_right(exc): try: yield finally: raise exc exc1 = Exception(1) exc2 = Exception(2) exc3 = Exception(3) exc4 = Exception(4) # The contextmanager already fixes the context, so prior to the # fix, ExitStack would try to fix it *again* and get into an # infinite self-referential loop try: with self.exit_stack() as stack: stack.enter_context(gets_the_context_right(exc4)) stack.enter_context(gets_the_context_right(exc3)) stack.enter_context(gets_the_context_right(exc2)) raise exc1 except Exception as exc: self.assertIs(exc, exc4) self.assertIs(exc.__context__, exc3) self.assertIs(exc.__context__.__context__, exc2) self.assertIs(exc.__context__.__context__.__context__, exc1) self.assertIsNone( exc.__context__.__context__.__context__.__context__) def test_exit_exception_with_existing_context(self): # Addresses a lack of test coverage discovered after checking in a # fix for issue 20317 that still contained debugging code. def raise_nested(inner_exc, outer_exc): try: raise inner_exc finally: raise outer_exc exc1 = Exception(1) exc2 = Exception(2) exc3 = Exception(3) exc4 = Exception(4) exc5 = Exception(5) try: with self.exit_stack() as stack: stack.callback(raise_nested, exc4, exc5) stack.callback(raise_nested, exc2, exc3) raise exc1 except Exception as exc: self.assertIs(exc, exc5) self.assertIs(exc.__context__, exc4) self.assertIs(exc.__context__.__context__, exc3) self.assertIs(exc.__context__.__context__.__context__, exc2) self.assertIs( exc.__context__.__context__.__context__.__context__, exc1) self.assertIsNone( exc.__context__.__context__.__context__.__context__.__context__) def test_body_exception_suppress(self): def suppress_exc(*exc_details): return True try: with self.exit_stack() as stack: stack.push(suppress_exc) 1/0 except IndexError as exc: self.fail("Expected no exception, got IndexError") def test_exit_exception_chaining_suppress(self): with self.exit_stack() as stack: stack.push(lambda *exc: True) stack.push(lambda *exc: 1/0) stack.push(lambda *exc: {}[1]) def test_excessive_nesting(self): # The original implementation would die with RecursionError here with self.exit_stack() as stack: for i in range(10000): stack.callback(int) def test_instance_bypass(self): class Example(object): pass cm = Example() cm.__exit__ = object() stack = self.exit_stack() self.assertRaises(AttributeError, stack.enter_context, cm) stack.push(cm) self.assertIs(stack._exit_callbacks[-1][1], cm) def test_dont_reraise_RuntimeError(self): # https://bugs.python.org/issue27122 class UniqueException(Exception): pass class UniqueRuntimeError(RuntimeError): pass @contextmanager def second(): try: yield 1 except Exception as exc: raise UniqueException("new exception") from exc @contextmanager def first(): try: yield 1 except Exception as exc: raise exc # The UniqueRuntimeError should be caught by second()'s exception # handler which chain raised a new UniqueException. with self.assertRaises(UniqueException) as err_ctx: with self.exit_stack() as es_ctx: es_ctx.enter_context(second()) es_ctx.enter_context(first()) raise UniqueRuntimeError("please no infinite loop.") exc = err_ctx.exception self.assertIsInstance(exc, UniqueException) self.assertIsInstance(exc.__context__, UniqueRuntimeError) self.assertIsNone(exc.__context__.__context__) self.assertIsNone(exc.__context__.__cause__) self.assertIs(exc.__cause__, exc.__context__) class TestExitStack(TestBaseExitStack, unittest.TestCase): exit_stack = ExitStack class TestRedirectStream: redirect_stream = None orig_stream = None @support.requires_docstrings def test_instance_docs(self): # Issue 19330: ensure context manager instances have good docstrings cm_docstring = self.redirect_stream.__doc__ obj = self.redirect_stream(None) self.assertEqual(obj.__doc__, cm_docstring) def test_no_redirect_in_init(self): orig_stdout = getattr(sys, self.orig_stream) self.redirect_stream(None) self.assertIs(getattr(sys, self.orig_stream), orig_stdout) def test_redirect_to_string_io(self): f = io.StringIO() msg = "Consider an API like help(), which prints directly to stdout" orig_stdout = getattr(sys, self.orig_stream) with self.redirect_stream(f): print(msg, file=getattr(sys, self.orig_stream)) self.assertIs(getattr(sys, self.orig_stream), orig_stdout) s = f.getvalue().strip() self.assertEqual(s, msg) def test_enter_result_is_target(self): f = io.StringIO() with self.redirect_stream(f) as enter_result: self.assertIs(enter_result, f) def test_cm_is_reusable(self): f = io.StringIO() write_to_f = self.redirect_stream(f) orig_stdout = getattr(sys, self.orig_stream) with write_to_f: print("Hello", end=" ", file=getattr(sys, self.orig_stream)) with write_to_f: print("World!", file=getattr(sys, self.orig_stream)) self.assertIs(getattr(sys, self.orig_stream), orig_stdout) s = f.getvalue() self.assertEqual(s, "Hello World!\n") def test_cm_is_reentrant(self): f = io.StringIO() write_to_f = self.redirect_stream(f) orig_stdout = getattr(sys, self.orig_stream) with write_to_f: print("Hello", end=" ", file=getattr(sys, self.orig_stream)) with write_to_f: print("World!", file=getattr(sys, self.orig_stream)) self.assertIs(getattr(sys, self.orig_stream), orig_stdout) s = f.getvalue() self.assertEqual(s, "Hello World!\n") class TestRedirectStdout(TestRedirectStream, unittest.TestCase): redirect_stream = redirect_stdout orig_stream = "stdout" class TestRedirectStderr(TestRedirectStream, unittest.TestCase): redirect_stream = redirect_stderr orig_stream = "stderr" class TestSuppress(unittest.TestCase): @support.requires_docstrings def test_instance_docs(self): # Issue 19330: ensure context manager instances have good docstrings cm_docstring = suppress.__doc__ obj = suppress() self.assertEqual(obj.__doc__, cm_docstring) def test_no_result_from_enter(self): with suppress(ValueError) as enter_result: self.assertIsNone(enter_result) def test_no_exception(self): with suppress(ValueError): self.assertEqual(pow(2, 5), 32) def test_exact_exception(self): with suppress(TypeError): len(5) def test_exception_hierarchy(self): with suppress(LookupError): 'Hello'[50] def test_other_exception(self): with self.assertRaises(ZeroDivisionError): with suppress(TypeError): 1/0 def test_no_args(self): with self.assertRaises(ZeroDivisionError): with suppress(): 1/0 def test_multiple_exception_args(self): with suppress(ZeroDivisionError, TypeError): 1/0 with suppress(ZeroDivisionError, TypeError): len(5) def test_cm_is_reentrant(self): ignore_exceptions = suppress(Exception) with ignore_exceptions: pass with ignore_exceptions: len(5) with ignore_exceptions: with ignore_exceptions: # Check nested usage len(5) outer_continued = True 1/0 self.assertTrue(outer_continued) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/test/test_contextlib_async.py0000644000175100001710000004234300000000000021343 0ustar00runnerdockerimport asyncio from contextlib2 import ( asynccontextmanager, AbstractAsyncContextManager, AsyncExitStack, nullcontext, aclosing, contextmanager) import functools from test import support import unittest from test.test_contextlib import TestBaseExitStack def _async_test(func): """Decorator to turn an async function into a test case.""" @functools.wraps(func) def wrapper(*args, **kwargs): coro = func(*args, **kwargs) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: return loop.run_until_complete(coro) finally: loop.close() asyncio.set_event_loop_policy(None) return wrapper class TestAbstractAsyncContextManager(unittest.TestCase): @_async_test async def test_enter(self): class DefaultEnter(AbstractAsyncContextManager): async def __aexit__(self, *args): await super().__aexit__(*args) manager = DefaultEnter() self.assertIs(await manager.__aenter__(), manager) async with manager as context: self.assertIs(manager, context) @_async_test async def test_async_gen_propagates_generator_exit(self): # A regression test for https://bugs.python.org/issue33786. @asynccontextmanager async def ctx(): yield async def gen(): async with ctx(): yield 11 ret = [] exc = ValueError(22) with self.assertRaises(ValueError): async with ctx(): async for val in gen(): ret.append(val) raise exc self.assertEqual(ret, [11]) def test_exit_is_abstract(self): class MissingAexit(AbstractAsyncContextManager): pass with self.assertRaises(TypeError): MissingAexit() def test_structural_subclassing(self): class ManagerFromScratch: async def __aenter__(self): return self async def __aexit__(self, exc_type, exc_value, traceback): return None self.assertTrue(issubclass(ManagerFromScratch, AbstractAsyncContextManager)) class DefaultEnter(AbstractAsyncContextManager): async def __aexit__(self, *args): await super().__aexit__(*args) self.assertTrue(issubclass(DefaultEnter, AbstractAsyncContextManager)) class NoneAenter(ManagerFromScratch): __aenter__ = None self.assertFalse(issubclass(NoneAenter, AbstractAsyncContextManager)) class NoneAexit(ManagerFromScratch): __aexit__ = None self.assertFalse(issubclass(NoneAexit, AbstractAsyncContextManager)) class AsyncContextManagerTestCase(unittest.TestCase): @_async_test async def test_contextmanager_plain(self): state = [] @asynccontextmanager async def woohoo(): state.append(1) yield 42 state.append(999) async with woohoo() as x: self.assertEqual(state, [1]) self.assertEqual(x, 42) state.append(x) self.assertEqual(state, [1, 42, 999]) @_async_test async def test_contextmanager_finally(self): state = [] @asynccontextmanager async def woohoo(): state.append(1) try: yield 42 finally: state.append(999) with self.assertRaises(ZeroDivisionError): async with woohoo() as x: self.assertEqual(state, [1]) self.assertEqual(x, 42) state.append(x) raise ZeroDivisionError() self.assertEqual(state, [1, 42, 999]) @_async_test async def test_contextmanager_no_reraise(self): @asynccontextmanager async def whee(): yield ctx = whee() await ctx.__aenter__() # Calling __aexit__ should not result in an exception self.assertFalse(await ctx.__aexit__(TypeError, TypeError("foo"), None)) @_async_test async def test_contextmanager_trap_yield_after_throw(self): @asynccontextmanager async def whoo(): try: yield except: yield ctx = whoo() await ctx.__aenter__() with self.assertRaises(RuntimeError): await ctx.__aexit__(TypeError, TypeError('foo'), None) @_async_test async def test_contextmanager_trap_no_yield(self): @asynccontextmanager async def whoo(): if False: yield ctx = whoo() with self.assertRaises(RuntimeError): await ctx.__aenter__() @_async_test async def test_contextmanager_trap_second_yield(self): @asynccontextmanager async def whoo(): yield yield ctx = whoo() await ctx.__aenter__() with self.assertRaises(RuntimeError): await ctx.__aexit__(None, None, None) @_async_test async def test_contextmanager_non_normalised(self): @asynccontextmanager async def whoo(): try: yield except RuntimeError: raise SyntaxError ctx = whoo() await ctx.__aenter__() with self.assertRaises(SyntaxError): await ctx.__aexit__(RuntimeError, None, None) @_async_test async def test_contextmanager_except(self): state = [] @asynccontextmanager async def woohoo(): state.append(1) try: yield 42 except ZeroDivisionError as e: state.append(e.args[0]) self.assertEqual(state, [1, 42, 999]) async with woohoo() as x: self.assertEqual(state, [1]) self.assertEqual(x, 42) state.append(x) raise ZeroDivisionError(999) self.assertEqual(state, [1, 42, 999]) @_async_test async def test_contextmanager_except_stopiter(self): @asynccontextmanager async def woohoo(): yield for stop_exc in (StopIteration('spam'), StopAsyncIteration('ham')): with self.subTest(type=type(stop_exc)): try: async with woohoo(): raise stop_exc except Exception as ex: self.assertIs(ex, stop_exc) else: self.fail(f'{stop_exc} was suppressed') @_async_test async def test_contextmanager_wrap_runtimeerror(self): @asynccontextmanager async def woohoo(): try: yield except Exception as exc: raise RuntimeError(f'caught {exc}') from exc with self.assertRaises(RuntimeError): async with woohoo(): 1 / 0 # If the context manager wrapped StopAsyncIteration in a RuntimeError, # we also unwrap it, because we can't tell whether the wrapping was # done by the generator machinery or by the generator itself. with self.assertRaises(StopAsyncIteration): async with woohoo(): raise StopAsyncIteration def _create_contextmanager_attribs(self): def attribs(**kw): def decorate(func): for k,v in kw.items(): setattr(func,k,v) return func return decorate @asynccontextmanager @attribs(foo='bar') async def baz(spam): """Whee!""" yield return baz def test_contextmanager_attribs(self): baz = self._create_contextmanager_attribs() self.assertEqual(baz.__name__,'baz') self.assertEqual(baz.foo, 'bar') @support.requires_docstrings def test_contextmanager_doc_attrib(self): baz = self._create_contextmanager_attribs() self.assertEqual(baz.__doc__, "Whee!") @support.requires_docstrings @_async_test async def test_instance_docstring_given_cm_docstring(self): baz = self._create_contextmanager_attribs()(None) self.assertEqual(baz.__doc__, "Whee!") async with baz: pass # suppress warning @_async_test async def test_keywords(self): # Ensure no keyword arguments are inhibited @asynccontextmanager async def woohoo(self, func, args, kwds): yield (self, func, args, kwds) async with woohoo(self=11, func=22, args=33, kwds=44) as target: self.assertEqual(target, (11, 22, 33, 44)) @_async_test async def test_recursive(self): depth = 0 ncols = 0 @asynccontextmanager async def woohoo(): nonlocal ncols ncols += 1 nonlocal depth before = depth depth += 1 yield depth -= 1 self.assertEqual(depth, before) @woohoo() async def recursive(): if depth < 10: await recursive() await recursive() self.assertEqual(ncols, 10) self.assertEqual(depth, 0) class AclosingTestCase(unittest.TestCase): @support.requires_docstrings def test_instance_docs(self): cm_docstring = aclosing.__doc__ obj = aclosing(None) self.assertEqual(obj.__doc__, cm_docstring) @_async_test async def test_aclosing(self): state = [] class C: async def aclose(self): state.append(1) x = C() self.assertEqual(state, []) async with aclosing(x) as y: self.assertEqual(x, y) self.assertEqual(state, [1]) @_async_test async def test_aclosing_error(self): state = [] class C: async def aclose(self): state.append(1) x = C() self.assertEqual(state, []) with self.assertRaises(ZeroDivisionError): async with aclosing(x) as y: self.assertEqual(x, y) 1 / 0 self.assertEqual(state, [1]) @_async_test async def test_aclosing_bpo41229(self): state = [] @contextmanager def sync_resource(): try: yield finally: state.append(1) async def agenfunc(): with sync_resource(): yield -1 yield -2 x = agenfunc() self.assertEqual(state, []) with self.assertRaises(ZeroDivisionError): async with aclosing(x) as y: self.assertEqual(x, y) self.assertEqual(-1, await x.__anext__()) 1 / 0 self.assertEqual(state, [1]) class TestAsyncExitStack(TestBaseExitStack, unittest.TestCase): class SyncAsyncExitStack(AsyncExitStack): @staticmethod def run_coroutine(coro): loop = asyncio.get_event_loop_policy().get_event_loop() t = loop.create_task(coro) t.add_done_callback(lambda f: loop.stop()) loop.run_forever() exc = t.exception() if not exc: return t.result() else: context = exc.__context__ try: raise exc except: exc.__context__ = context raise exc def close(self): return self.run_coroutine(self.aclose()) def __enter__(self): return self.run_coroutine(self.__aenter__()) def __exit__(self, *exc_details): return self.run_coroutine(self.__aexit__(*exc_details)) exit_stack = SyncAsyncExitStack def setUp(self): self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) self.addCleanup(self.loop.close) self.addCleanup(asyncio.set_event_loop_policy, None) @_async_test async def test_async_callback(self): expected = [ ((), {}), ((1,), {}), ((1,2), {}), ((), dict(example=1)), ((1,), dict(example=1)), ((1,2), dict(example=1)), ] result = [] async def _exit(*args, **kwds): """Test metadata propagation""" result.append((args, kwds)) async with AsyncExitStack() as stack: for args, kwds in reversed(expected): if args and kwds: f = stack.push_async_callback(_exit, *args, **kwds) elif args: f = stack.push_async_callback(_exit, *args) elif kwds: f = stack.push_async_callback(_exit, **kwds) else: f = stack.push_async_callback(_exit) self.assertIs(f, _exit) for wrapper in stack._exit_callbacks: self.assertIs(wrapper[1].__wrapped__, _exit) self.assertNotEqual(wrapper[1].__name__, _exit.__name__) self.assertIsNone(wrapper[1].__doc__, _exit.__doc__) self.assertEqual(result, expected) result = [] async with AsyncExitStack() as stack: with self.assertRaises(TypeError): stack.push_async_callback(arg=1) with self.assertRaises(TypeError): self.exit_stack.push_async_callback(arg=2) with self.assertRaises(TypeError): stack.push_async_callback(callback=_exit, arg=3) self.assertEqual(result, []) @_async_test async def test_async_push(self): exc_raised = ZeroDivisionError async def _expect_exc(exc_type, exc, exc_tb): self.assertIs(exc_type, exc_raised) async def _suppress_exc(*exc_details): return True async def _expect_ok(exc_type, exc, exc_tb): self.assertIsNone(exc_type) self.assertIsNone(exc) self.assertIsNone(exc_tb) class ExitCM(object): def __init__(self, check_exc): self.check_exc = check_exc async def __aenter__(self): self.fail("Should not be called!") async def __aexit__(self, *exc_details): await self.check_exc(*exc_details) async with self.exit_stack() as stack: stack.push_async_exit(_expect_ok) self.assertIs(stack._exit_callbacks[-1][1], _expect_ok) cm = ExitCM(_expect_ok) stack.push_async_exit(cm) self.assertIs(stack._exit_callbacks[-1][1].__self__, cm) stack.push_async_exit(_suppress_exc) self.assertIs(stack._exit_callbacks[-1][1], _suppress_exc) cm = ExitCM(_expect_exc) stack.push_async_exit(cm) self.assertIs(stack._exit_callbacks[-1][1].__self__, cm) stack.push_async_exit(_expect_exc) self.assertIs(stack._exit_callbacks[-1][1], _expect_exc) stack.push_async_exit(_expect_exc) self.assertIs(stack._exit_callbacks[-1][1], _expect_exc) 1/0 @_async_test async def test_async_enter_context(self): class TestCM(object): async def __aenter__(self): result.append(1) async def __aexit__(self, *exc_details): result.append(3) result = [] cm = TestCM() async with AsyncExitStack() as stack: @stack.push_async_callback # Registered first => cleaned up last async def _exit(): result.append(4) self.assertIsNotNone(_exit) await stack.enter_async_context(cm) self.assertIs(stack._exit_callbacks[-1][1].__self__, cm) result.append(2) self.assertEqual(result, [1, 2, 3, 4]) @_async_test async def test_async_exit_exception_chaining(self): # Ensure exception chaining matches the reference behaviour async def raise_exc(exc): raise exc saved_details = None async def suppress_exc(*exc_details): nonlocal saved_details saved_details = exc_details return True try: async with self.exit_stack() as stack: stack.push_async_callback(raise_exc, IndexError) stack.push_async_callback(raise_exc, KeyError) stack.push_async_callback(raise_exc, AttributeError) stack.push_async_exit(suppress_exc) stack.push_async_callback(raise_exc, ValueError) 1 / 0 except IndexError as exc: self.assertIsInstance(exc.__context__, KeyError) self.assertIsInstance(exc.__context__.__context__, AttributeError) # Inner exceptions were suppressed self.assertIsNone(exc.__context__.__context__.__context__) else: self.fail("Expected IndexError, but no exception was raised") # Check the inner exceptions inner_exc = saved_details[1] self.assertIsInstance(inner_exc, ValueError) self.assertIsInstance(inner_exc.__context__, ZeroDivisionError) class TestAsyncNullcontext(unittest.TestCase): @_async_test async def test_async_nullcontext(self): class C: pass c = C() async with nullcontext(c) as c_in: self.assertIs(c_in, c) if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1624775914.0 contextlib2-21.6.0/tox.ini0000644000175100001710000000074700000000000014720 0ustar00runnerdocker[tox] envlist = py{36,37,38,39,3_10,py3} skip_missing_interpreters = True [testenv] commands = coverage run -m unittest discover -t . -s test coverage report coverage xml # mypy won't install on PyPy, so only run the typechecking on CPython !pypy3: python -m mypy.stubtest --allowlist dev/mypy.allowlist contextlib2 deps = coverage !pypy3: mypy [gh-actions] python = 3.6: py36 3.7: py37 3.8: py38 3.9: py39 3.10: py3_10 pypy3: pypy3