From 0077233514f68e6187772029aabd80d07bbaec09 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 13 Dec 2011 22:41:17 +1000 Subject: [PATCH 01/28] Initial project commit --- .hgignore | 16 ++ LICENSE.txt | 122 ++++++++++++++ README.txt | 3 + contextlib2.py | 220 ++++++++++++++++++++++++++ docs/Makefile | 130 +++++++++++++++ docs/conf.py | 220 ++++++++++++++++++++++++++ docs/index.rst | 266 +++++++++++++++++++++++++++++++ docs/make.bat | 170 ++++++++++++++++++++ setup.py | 13 ++ test_contextlib2.py | 376 ++++++++++++++++++++++++++++++++++++++++++++ 10 files changed, 1536 insertions(+) create mode 100644 .hgignore create mode 100644 LICENSE.txt create mode 100644 README.txt create mode 100644 contextlib2.py create mode 100644 docs/Makefile create mode 100644 docs/conf.py create mode 100644 docs/index.rst create mode 100644 docs/make.bat create mode 100644 setup.py create mode 100644 test_contextlib2.py diff --git a/.hgignore b/.hgignore new file mode 100644 index 0000000..37ca46e --- /dev/null +++ b/.hgignore @@ -0,0 +1,16 @@ +syntax: glob +*.swp +*.kate-swp +*.o +*.pyc +*.pyo +*.pyd +*.cover +*~ +__pycache__ +.coverage +coverage/ +htmlcov/ +_build/ +dist/ +MANIFEST \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..5de2027 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,122 @@ + + +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. diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..3bf4588 --- /dev/null +++ b/README.txt @@ -0,0 +1,3 @@ +contextlib2 is a backport of the standard library's contextlib module to earlier Python versions. + +It also serves as a real world proving ground for possible future enhancements to the standard library version. diff --git a/contextlib2.py b/contextlib2.py new file mode 100644 index 0000000..f9c9d66 --- /dev/null +++ b/contextlib2.py @@ -0,0 +1,220 @@ +"""contextlib2 - backports and enhancements to the contextlib module""" + +import sys +from collections import deque +from functools import wraps + +__all__ = ["contextmanager", "closing", "ContextDecorator", "CleanupManager"] + + +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. + """ + return self + + def __call__(self, func): + @wraps(func) + def inner(*args, **kwds): + with self.refresh_cm(): + return func(*args, **kwds) + return inner + + +class _GeneratorContextManager(ContextDecorator): + """Helper for @contextmanager decorator.""" + + def __init__(self, func, *args, **kwds): + self.gen = func(*args, **kwds) + self.func, self.args, self.kwds = func, args, kwds + + def refresh_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): + try: + return next(self.gen) + except StopIteration: + raise RuntimeError("generator didn't yield") + + def __exit__(self, type, value, traceback): + if type is None: + try: + next(self.gen) + except StopIteration: + return + 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) + raise RuntimeError("generator didn't stop after throw()") + except StopIteration as exc: + # Suppress the exception *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: + # 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. + # + if sys.exc_info()[1] 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 + + +class closing(object): + """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 CleanupManager(object): + """Context for programmatic management of resource cleanup + + For example: + + with CleanupManager() as cmgr: + files = [cmgr.enter_context(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 throw an exception + + """ + def __init__(self): + self._callbacks = deque() + + def register_exit(self, exit): + """Accepts callbacks with the same signature as context manager __exit__ methods + + Can also suppress exceptions the same way __exit__ methods can. + """ + self._callbacks.append(exit) + return exit # Allow use as a decorator + + def register(self, _cb, *args, **kwds): + """Accepts arbitrary callbacks and arguments. Cannot suppress exceptions.""" + def _wrapper(exc_type, exc, tb): + _cb(*args, **kwds) + return self.register_exit(_wrapper) + + def enter_context(self, cm): + """Accepts and automatically enters other context managers""" + # 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) + def _exit_wrapper(*exc_details): + return _exit(cm, *exc_details) + self.register_exit(_exit_wrapper) + return result + + def close(self): + """Immediately cleanup all registered resources""" + self.__exit__(None, None, None) + + def __enter__(self): + return self + + def __exit__(self, *exc_details): + if not self._callbacks: + return + # This looks complicated, but it is really just + # setting up a chain of try-expect statements to ensure + # that outer callbacks still get invoked even if an + # inner one throws an exception + def _invoke_next_callback(exc_details): + # Callbacks are removed from the list in FIFO order + # but the recursion means they're *invoked* in LIFO order + cb = self._callbacks.popleft() + if not self._callbacks: + # Innermost callback is invoked directly + return cb(*exc_details) + # More callbacks left, so descend another level in the stack + try: + suppress_exc = _invoke_next_callback(exc_details) + except: + suppress_exc = cb(*sys.exc_info()) + # Check if this cb suppressed the inner exception + if not suppress_exc: + raise + else: + # Check if inner cb suppressed the original exception + if suppress_exc: + exc_details = (None, None, None) + suppress_exc = cb(*exc_details) or suppress_exc + return suppress_exc + # Kick off the recursive chain + return _invoke_next_callback(exc_details) \ No newline at end of file diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..76f0bb2 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,130 @@ +# 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." diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..8791d73 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,220 @@ +# -*- 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'2011, 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. +version = '0.1' +# The full version, including alpha/beta/rc tags. +release = '0.1' + +# 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) +] + + +# Example configuration for intersphinx: refer to the Python 3 standard library. +intersphinx_mapping = {'http://docs.python.org/py3k': None} diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..6fd7427 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,266 @@ +.. 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 with-statement contexts +============================================================= + +.. 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`` statement. + + +Additions Relative to the Standard Library +------------------------------------------ + +This module is primarily a backport of the Python 3.2 version of +:mod:`contextlib` to earlier releases. However, it is also a proving ground +for new features not yet part of the standard library. Those new features +are currently: + +* :meth:`ContextDecorator.refresh_cm` +* :class:`CleanupManager` + + +API Reference +------------- + +.. function:: @contextmanager + + This function is a decorator that can be used to define a factory + function for ``with`` statement context managers, without needing to + create a class or separate :meth:`__enter__` and :meth:`__exit__` methods. + + A simple example (this is not recommended as a real way of generating HTML!):: + + from contextlib import contextmanager + + @contextmanager + def tag(name): + print("<%s>" % name) + yield + print("" % name) + + >>> with tag("h1"): + ... print("foo") + ... +

+ foo +

+ + The function being decorated must return a generator-iterator when + called. This iterator must yield exactly one value, which will be bound to + the targets in the ``with`` statement's ``as`` clause, if any. + + At the point where the generator yields, the block nested in the ``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 + ``try``...\ ``except``...\ ``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 ``with`` statement that + the exception has been handled, and execution will resume with the statement + immediately following the ``with`` statement. + + :func:`contextmanager` uses :class:`ContextDecorator` so the context managers + it creates can be used as decorators as well as in ``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). + + +.. 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 ``with`` block is exited. + + +.. 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 + :meth:`__enter__` and :meth:`__exit__` as normal. :meth:`__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 + + .. method:: refresh_cm() + + This method is invoked each time a call is made to a decorated function. + The default implementation just returns *self*. + + As the decorated function must be able to be called multiple times, the + underlying context manager must normally support use in multiple + ``with`` statements (preferably in a thread-safe manner). If + this is not the case, then the context manager must define this method + and return a *new* copy of the context manager on each invocation. + + This may involve keeping a copy of the original arguments used to + first initialise the context manager. + +.. class:: CleanupManager() + + A context manager that is designed to make it easy to programmatically + combine other context managers and cleanup functions, that are either + optional or driven by input data. + + For example, a set of files may easily be handled in a single with + statement as follows:: + + with CleanupManager() as cmgr: + files = [cmgr.enter_context(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 throw an exception + + .. method:: register_exit(exit): + + Accepts callbacks with the same signature as context manager + :meth:`__exit__` methods + + By returing true values, these callbacks can suppress exceptions the + same way context manager :meth:`__exit__` methods can. + + .. method:: register(_cb, *args, **kwds): + + Accepts arbitrary callbacks and arguments. These callbacks cannot + suppress exceptions. + + .. method:: enter_context(cm): + + Accepts and automatically enters other context managers. These + context managers may suppress exceptions just as they normally would. + + .. method:: close() + + Immediately cleans up all registered resources, resetting the manager + to its initial state in the process. + + +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 2.7 and 3.2+. + +.. _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 +----------------------- + +WalkDir is developed and maintained on BitBucket_. Problems and suggested +improvements can be posted to the `issue tracker`_. + +.. _BitBucket: https://bitbucket.org/ncoghlan/contextlib2/overview +.. _issue tracker: https://bitbucket.org/ncoghlan/contextlib2/issues?status=new&status=open + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`search` + diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..f6669e0 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,170 @@ +@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 diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..24962f9 --- /dev/null +++ b/setup.py @@ -0,0 +1,13 @@ +from distutils.core import setup + +setup( + name='contextlib2', + version='0.1', + py_modules=['contextlib2'], + license='PSF License', + description='Backports and enhancements for the contextlib module', + long_description=open('README.txt').read(), + author='Nick Coghlan', + author_email='ncoghlan@gmail.com', + url='http://contextlib2.readthedocs.org' +) diff --git a/test_contextlib2.py b/test_contextlib2.py new file mode 100644 index 0000000..64f8086 --- /dev/null +++ b/test_contextlib2.py @@ -0,0 +1,376 @@ +"""Unit tests for contextlib.py, and other context managers.""" + +import sys +import unittest + +from contextlib2 import * # Tests __all__ + + +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 _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') + + @unittest.skipIf(sys.flags.optimize >= 2, + "Docstrings are omitted with -O2 and above") + def test_contextmanager_doc_attrib(self): + baz = self._create_contextmanager_attribs() + self.assertEqual(baz.__doc__, "Whee!") + +class ClosingTestCase(unittest.TestCase): + + # XXX This needs more work + + 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 mycontext(ContextDecorator): + 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): + + 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.assertRaises(NameError): + with context: + raise NameError('foo') + self.assertIsNotNone(context.exc) + self.assertIs(context.exc[0], NameError) + self.assertIn('foo', context.exc[1]) + + 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.assertRaises(NameError): + test() + self.assertIsNotNone(context.exc) + self.assertIs(context.exc[0], NameError) + self.assertIn('foo', context.exc[1]) + + + 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 TestCleanupManager(unittest.TestCase): + + def test_no_resources(self): + with CleanupManager(): + pass + + def test_register(self): + expected = [ + ((), {}), + ((1,), {}), + ((1,2), {}), + ((), dict(example=1)), + ((1,), dict(example=1)), + ((1,2), dict(example=1)), + ] + result = [] + def _exit(*args, **kwds): + result.append((args, kwds)) + with CleanupManager() as cmgr: + for args, kwds in reversed(expected): + if args and kwds: + cmgr.register(_exit, *args, **kwds) + elif args: + cmgr.register(_exit, *args) + elif kwds: + cmgr.register(_exit, **kwds) + else: + cmgr.register(_exit) + + def test_register_exit(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) + with CleanupManager() as cmgr: + cmgr.register_exit(_expect_ok) + cmgr.register_exit(_suppress_exc) + cmgr.register_exit(_expect_exc) + cmgr.register_exit(_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 = [] + with CleanupManager() as cmgr: + @cmgr.register # Registered first => cleaned up last + def _exit(): + result.append(4) + cmgr.enter_context(TestCM()) + result.append(2) + self.assertEqual(result, [1, 2, 3, 4]) + + def test_close(self): + result = [] + with CleanupManager() as cmgr: + @cmgr.register # Registered first => cleaned up last + def _exit(): + result.append(1) + cmgr.close() + result.append(2) + self.assertEqual(result, [1, 2]) + + +if __name__ == "__main__": + test_main() From 4e624974a659ef2ab3f22a7bc96d0a87e2b02616 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Thu, 15 Dec 2011 21:07:03 +1000 Subject: [PATCH 02/28] Rename CleanupManager to ContextStack and fix usage of the test module as __main__ --- contextlib2.py | 37 +++++++++++++++---------- docs/index.rst | 67 ++++++++++++++++++++++++++++++--------------- setup.py | 2 +- test_contextlib2.py | 43 +++++++++++++++-------------- 4 files changed, 90 insertions(+), 59 deletions(-) mode change 100644 => 100755 test_contextlib2.py diff --git a/contextlib2.py b/contextlib2.py index f9c9d66..f99bbee 100644 --- a/contextlib2.py +++ b/contextlib2.py @@ -4,7 +4,7 @@ import sys from collections import deque from functools import wraps -__all__ = ["contextmanager", "closing", "ContextDecorator", "CleanupManager"] +__all__ = ["contextmanager", "closing", "ContextDecorator", "ContextStack"] class ContextDecorator(object): @@ -141,13 +141,13 @@ class closing(object): self.thing.close() -class CleanupManager(object): +class ContextStack(object): """Context for programmatic management of resource cleanup For example: - with CleanupManager() as cmgr: - files = [cmgr.enter_context(fname) for fname in filenames] + with ContextStack() as stack: + files = [stack.enter_context(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 throw an exception @@ -156,22 +156,29 @@ class CleanupManager(object): def __init__(self): self._callbacks = deque() - def register_exit(self, exit): - """Accepts callbacks with the same signature as context manager __exit__ methods + def register_exit(self, callback): + """Registers a callback with the standard __exit__ method signature - Can also suppress exceptions the same way __exit__ methods can. + Can suppress exceptions the same way __exit__ methods can. """ - self._callbacks.append(exit) - return exit # Allow use as a decorator + self._callbacks.append(callback) + return callback # Allow use as a decorator - def register(self, _cb, *args, **kwds): - """Accepts arbitrary callbacks and arguments. Cannot suppress exceptions.""" + def register(self, callback, *args, **kwds): + """Registers an arbitrary callback and arguments. + + Cannot suppress exceptions. + """ def _wrapper(exc_type, exc, tb): - _cb(*args, **kwds) + callback(*args, **kwds) return self.register_exit(_wrapper) def enter_context(self, cm): - """Accepts and automatically enters other context managers""" + """Enters the supplied context manager + + If successful, also registers 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__ @@ -182,7 +189,7 @@ class CleanupManager(object): return result def close(self): - """Immediately cleanup all registered resources""" + """Immediately unwind the context stack""" self.__exit__(None, None, None) def __enter__(self): @@ -197,7 +204,7 @@ class CleanupManager(object): # inner one throws an exception def _invoke_next_callback(exc_details): # Callbacks are removed from the list in FIFO order - # but the recursion means they're *invoked* in LIFO order + # but the recursion means they're invoked in LIFO order cb = self._callbacks.popleft() if not self._callbacks: # Innermost callback is invoked directly diff --git a/docs/index.rst b/docs/index.rst index 6fd7427..5928a30 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -188,43 +188,66 @@ API Reference This may involve keeping a copy of the original arguments used to first initialise the context manager. -.. class:: CleanupManager() + +.. class:: ContextStack() A context manager that is designed to make it easy to programmatically - combine other context managers and cleanup functions, that are either - optional or driven by input data. + 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 CleanupManager() as cmgr: - files = [cmgr.enter_context(fname) for fname in filenames] + with ContextStack() as stack: + files = [stack.enter_context(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 throw an exception - .. method:: register_exit(exit): + Each instance maintains a stack of registered callbacks (usually context + manager exit methods) that are called in reverse order when the instance + is closed (either explicitly or implicitly at the end of a ``with`` + statement). - Accepts callbacks with the same signature as context manager - :meth:`__exit__` methods - - By returing true values, these callbacks can suppress exceptions the - same way context manager :meth:`__exit__` methods can. - - .. method:: register(_cb, *args, **kwds): - - Accepts arbitrary callbacks and arguments. These callbacks cannot - suppress exceptions. + Since registered callbacks are invoked in the reverse order of + registration, this ends up behaving as if multiple nested ``with`` + statements had been used with the registered set of resources. 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 + that updated state. .. method:: enter_context(cm): - Accepts and automatically enters other context managers. These - context managers may suppress exceptions just as they normally would. + 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 ``with`` statement. + + .. method:: register_exit(callback): + + Directly accepts a callback with the same signature as a + context manager's :meth:`__exit__` method and adds it to the callback + stack. + + By returning true values, these callbacks can suppress exceptions the + same way context manager :meth:`__exit__` methods can. + + .. method:: push_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). .. method:: close() - Immediately cleans up all registered resources, resetting the manager - to its initial state in the process. + Immediately unwinds the context 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. Obtaining the Module @@ -241,7 +264,7 @@ 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 2.7 and 3.2+. +Supported Python versions are currently 2.7 and 3.2+. .. _Python Package Index: http://pypi.python.org .. _pip: http://www.pip-installer.org @@ -251,7 +274,7 @@ Supported Python versions are 2.7 and 3.2+. Development and Support ----------------------- -WalkDir is developed and maintained on BitBucket_. Problems and suggested +contextlib2 is developed and maintained on BitBucket_. Problems and suggested improvements can be posted to the `issue tracker`_. .. _BitBucket: https://bitbucket.org/ncoghlan/contextlib2/overview diff --git a/setup.py b/setup.py index 24962f9..5c9d52f 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ from distutils.core import setup setup( name='contextlib2', - version='0.1', + version='0.2', py_modules=['contextlib2'], license='PSF License', description='Backports and enhancements for the contextlib module', diff --git a/test_contextlib2.py b/test_contextlib2.py old mode 100644 new mode 100755 index 64f8086..10f146c --- a/test_contextlib2.py +++ b/test_contextlib2.py @@ -163,7 +163,7 @@ class TestContextDecorator(unittest.TestCase): raise NameError('foo') self.assertIsNotNone(context.exc) self.assertIs(context.exc[0], NameError) - self.assertIn('foo', context.exc[1]) + self.assertIn('foo', str(context.exc[1])) context = mycontext() context.catch = True @@ -197,7 +197,7 @@ class TestContextDecorator(unittest.TestCase): test() self.assertIsNotNone(context.exc) self.assertIs(context.exc[0], NameError) - self.assertIn('foo', context.exc[1]) + self.assertIn('foo', str(context.exc[1])) def test_decorating_method(self): @@ -299,10 +299,10 @@ class TestContextDecorator(unittest.TestCase): self.assertEqual(state, [1, 'something else', 999]) -class TestCleanupManager(unittest.TestCase): +class TestContextStack(unittest.TestCase): def test_no_resources(self): - with CleanupManager(): + with ContextStack(): pass def test_register(self): @@ -317,16 +317,16 @@ class TestCleanupManager(unittest.TestCase): result = [] def _exit(*args, **kwds): result.append((args, kwds)) - with CleanupManager() as cmgr: + with ContextStack() as stack: for args, kwds in reversed(expected): if args and kwds: - cmgr.register(_exit, *args, **kwds) + stack.register(_exit, *args, **kwds) elif args: - cmgr.register(_exit, *args) + stack.register(_exit, *args) elif kwds: - cmgr.register(_exit, **kwds) + stack.register(_exit, **kwds) else: - cmgr.register(_exit) + stack.register(_exit) def test_register_exit(self): exc_raised = ZeroDivisionError @@ -338,11 +338,11 @@ class TestCleanupManager(unittest.TestCase): self.assertIsNone(exc_type) self.assertIsNone(exc) self.assertIsNone(exc_tb) - with CleanupManager() as cmgr: - cmgr.register_exit(_expect_ok) - cmgr.register_exit(_suppress_exc) - cmgr.register_exit(_expect_exc) - cmgr.register_exit(_expect_exc) + with ContextStack() as stack: + stack.register_exit(_expect_ok) + stack.register_exit(_suppress_exc) + stack.register_exit(_expect_exc) + stack.register_exit(_expect_exc) 1/0 def test_enter_context(self): @@ -353,24 +353,25 @@ class TestCleanupManager(unittest.TestCase): result.append(3) result = [] - with CleanupManager() as cmgr: - @cmgr.register # Registered first => cleaned up last + with ContextStack() as stack: + @stack.register # Registered first => cleaned up last def _exit(): result.append(4) - cmgr.enter_context(TestCM()) + stack.enter_context(TestCM()) result.append(2) self.assertEqual(result, [1, 2, 3, 4]) def test_close(self): result = [] - with CleanupManager() as cmgr: - @cmgr.register # Registered first => cleaned up last + with ContextStack() as stack: + @stack.register # Registered first => cleaned up last def _exit(): result.append(1) - cmgr.close() + stack.close() result.append(2) self.assertEqual(result, [1, 2]) if __name__ == "__main__": - test_main() + import unittest + unittest.main(__name__) From 0744d3cf63efa6ffbdf02bbf283f632700098099 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Thu, 15 Dec 2011 21:10:29 +1000 Subject: [PATCH 03/28] Oops, missed one reference to the initial name --- docs/index.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.rst b/docs/index.rst index 5928a30..93192aa 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -27,7 +27,7 @@ for new features not yet part of the standard library. Those new features are currently: * :meth:`ContextDecorator.refresh_cm` -* :class:`CleanupManager` +* :class:`ContextStack` API Reference From 9c4193acd0de451bee2a821bea350c6c49e38ee4 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Thu, 15 Dec 2011 21:11:05 +1000 Subject: [PATCH 04/28] Allow direct execution of setup.py as well --- setup.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 setup.py diff --git a/setup.py b/setup.py old mode 100644 new mode 100755 From c1d261921b4d1308871335b9f4e82a5d782cedb6 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Thu, 15 Dec 2011 21:13:03 +1000 Subject: [PATCH 05/28] If one is going to mark scripts executable, one had best add a shebang line... --- setup.py | 1 + test_contextlib2.py | 1 + 2 files changed, 2 insertions(+) diff --git a/setup.py b/setup.py index 5c9d52f..a30c65c 100755 --- a/setup.py +++ b/setup.py @@ -1,3 +1,4 @@ +#!/usr/bin/env python from distutils.core import setup setup( diff --git a/test_contextlib2.py b/test_contextlib2.py index 10f146c..eb96cf1 100755 --- a/test_contextlib2.py +++ b/test_contextlib2.py @@ -1,3 +1,4 @@ +#!/usr/bin/env python """Unit tests for contextlib.py, and other context managers.""" import sys From dbc0c6d23f77f0d2186df4e944d9333991770b13 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Thu, 15 Dec 2011 22:30:55 +1000 Subject: [PATCH 06/28] Add link back to original tracker issue, fix typo noticed by Chris Neugebauer --- contextlib2.py | 5 +++-- docs/index.rst | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/contextlib2.py b/contextlib2.py index f99bbee..f02a381 100644 --- a/contextlib2.py +++ b/contextlib2.py @@ -141,13 +141,14 @@ class closing(object): self.thing.close() +# Inspired by discussions on http://bugs.python.org/issue13585 class ContextStack(object): - """Context for programmatic management of resource cleanup + """Context manager for programmatic management of resource cleanup For example: with ContextStack() as stack: - files = [stack.enter_context(fname) for fname in filenames] + 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 throw an exception diff --git a/docs/index.rst b/docs/index.rst index 93192aa..e4be3a3 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -199,7 +199,7 @@ API Reference statement as follows:: with ContextStack() as stack: - files = [stack.enter_context(fname) for fname in filenames] + 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 throw an exception From dbfcb44e47afba44943f512cac34ed85f0fae61f Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Thu, 15 Dec 2011 23:02:22 +1000 Subject: [PATCH 07/28] Fix typo --- docs/index.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.rst b/docs/index.rst index e4be3a3..99e5084 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -214,7 +214,7 @@ API Reference statements had been used with the registered set of resources. 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 - that updated state. + updated state. .. method:: enter_context(cm): From 3fbd301c649aaac1ebed82e835b711d959549bf2 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Thu, 15 Dec 2011 23:03:23 +1000 Subject: [PATCH 08/28] Remove unnecessary colons --- docs/index.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/index.rst b/docs/index.rst index 99e5084..8892cdb 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -216,7 +216,7 @@ API Reference an exception, then outer callbacks will be passed arguments based on that updated state. - .. method:: enter_context(cm): + .. 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 @@ -225,7 +225,7 @@ API Reference These context managers may suppress exceptions just as they normally would if used directly as part of a ``with`` statement. - .. method:: register_exit(callback): + .. method:: register_exit(callback) Directly accepts a callback with the same signature as a context manager's :meth:`__exit__` method and adds it to the callback @@ -234,7 +234,7 @@ API Reference By returning true values, these callbacks can suppress exceptions the same way context manager :meth:`__exit__` methods can. - .. method:: push_callback(callback, *args, **kwds): + .. method:: push_callback(callback, *args, **kwds) Accepts an arbitrary callback function and arguments and adds it to the callback stack. From 22bbb22d212856c112fb71f852f2f8437816c0ef Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Thu, 15 Dec 2011 23:04:23 +1000 Subject: [PATCH 09/28] Fix method name in docs --- docs/index.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.rst b/docs/index.rst index 8892cdb..b2347c8 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -234,7 +234,7 @@ API Reference By returning true values, these callbacks can suppress exceptions the same way context manager :meth:`__exit__` methods can. - .. method:: push_callback(callback, *args, **kwds) + .. method:: register(callback, *args, **kwds) Accepts an arbitrary callback function and arguments and adds it to the callback stack. From 1da5ee6412b1477d5e16d70cd55aedd3624c87f9 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Fri, 16 Dec 2011 23:37:53 +1000 Subject: [PATCH 10/28] Move version number into a shared file read by both setup.py and docs/conf.py --- VERSION.txt | 1 + docs/conf.py | 7 ++++--- setup.py | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) create mode 100644 VERSION.txt diff --git a/VERSION.txt b/VERSION.txt new file mode 100644 index 0000000..2f45361 --- /dev/null +++ b/VERSION.txt @@ -0,0 +1 @@ +0.2 \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py index 8791d73..a660283 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,7 +16,7 @@ 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('.')) +# sys.path.insert(0, os.path.abspath('..')) # -- General configuration ----------------------------------------------------- @@ -48,9 +48,10 @@ copyright = u'2011, Nick Coghlan' # built documents. # # The short X.Y version. -version = '0.1' +with open('../VERSION.txt') as f: + version = f.read().strip() # The full version, including alpha/beta/rc tags. -release = '0.1' +release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/setup.py b/setup.py index a30c65c..1544eef 100755 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ from distutils.core import setup setup( name='contextlib2', - version='0.2', + version=open('VERSION.txt').read().strip(), py_modules=['contextlib2'], license='PSF License', description='Backports and enhancements for the contextlib module', From 2c9b2123847b69e01b7570a1426041611683431c Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Sun, 18 Dec 2011 18:09:52 +1000 Subject: [PATCH 11/28] Better version history information --- NEWS.rst | 25 +++++++++++++++++++++++++ docs/index.rst | 18 +++++++++++++----- 2 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 NEWS.rst diff --git a/NEWS.rst b/NEWS.rst new file mode 100644 index 0000000..9294e29 --- /dev/null +++ b/NEWS.rst @@ -0,0 +1,25 @@ +Release History +--------------- + + +0.3 (2011-12-XX) +~~~~~~~~~~~~~~~~ + +* 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 diff --git a/docs/index.rst b/docs/index.rst index b2347c8..dc89fe6 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -3,8 +3,8 @@ You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. -contextlib2 --- Updated utilities for with-statement contexts -============================================================= +contextlib2 --- Updated utilities for context management +======================================================== .. module:: contextlib2 :synopsis: Backports and future enhancements for the contextlib module @@ -26,12 +26,12 @@ This module is primarily a backport of the Python 3.2 version of for new features not yet part of the standard library. Those new features are currently: -* :meth:`ContextDecorator.refresh_cm` * :class:`ContextStack` +* :meth:`ContextDecorator.refresh_cm` API Reference -------------- +============= .. function:: @contextmanager @@ -188,6 +188,9 @@ API Reference This may involve keeping a copy of the original arguments used to first initialise the context manager. + .. versionchanged:: 0.1 + Made the standard library's private :meth:`refresh_cm` API public + .. class:: ContextStack() @@ -249,6 +252,9 @@ API Reference callbacks registered, the arguments passed in will indicate that no exception occurred. + .. versionadded:: 0.2 + New API for :mod:`contextlib2`, not available in standard library + Obtaining the Module ==================== @@ -281,9 +287,11 @@ improvements can be posted to the `issue tracker`_. .. _issue tracker: https://bitbucket.org/ncoghlan/contextlib2/issues?status=new&status=open +.. include:: ../NEWS.rst + + Indices and tables ================== * :ref:`genindex` * :ref:`search` - From 57bc54d8e4935b7c2d539a2836deff6e32189c52 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 3 Jan 2012 13:08:43 +1000 Subject: [PATCH 12/28] Version history tweaks for in development version --- NEWS.rst | 2 +- VERSION.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/NEWS.rst b/NEWS.rst index 9294e29..f83af61 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -2,7 +2,7 @@ Release History --------------- -0.3 (2011-12-XX) +0.3 (2012-01-XX) ~~~~~~~~~~~~~~~~ * Moved version number to a VERSION.txt file (read by both docs and setup.py) diff --git a/VERSION.txt b/VERSION.txt index 2f45361..f46a2c2 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1 +1 @@ -0.2 \ No newline at end of file +0.2+ \ No newline at end of file From 7f99236d3bf86ff1c6d1b86e96075a727e4ef05b Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 3 Jan 2012 14:00:18 +1000 Subject: [PATCH 13/28] Properly wrap callbacks in ContextStack.register() and actually assert something in TestContextStack.test_register() --- NEWS.rst | 1 + contextlib2.py | 1 + test_contextlib2.py | 5 +++++ 3 files changed, 7 insertions(+) diff --git a/NEWS.rst b/NEWS.rst index f83af61..dbb3c98 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -5,6 +5,7 @@ Release History 0.3 (2012-01-XX) ~~~~~~~~~~~~~~~~ +* Wrapped callbacks now use functools.wraps 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) diff --git a/contextlib2.py b/contextlib2.py index f02a381..65dd434 100644 --- a/contextlib2.py +++ b/contextlib2.py @@ -170,6 +170,7 @@ class ContextStack(object): Cannot suppress exceptions. """ + @wraps(callback) def _wrapper(exc_type, exc, tb): callback(*args, **kwds) return self.register_exit(_wrapper) diff --git a/test_contextlib2.py b/test_contextlib2.py index eb96cf1..7a3150b 100755 --- a/test_contextlib2.py +++ b/test_contextlib2.py @@ -317,6 +317,7 @@ class TestContextStack(unittest.TestCase): ] result = [] def _exit(*args, **kwds): + """Test metadata propagation""" result.append((args, kwds)) with ContextStack() as stack: for args, kwds in reversed(expected): @@ -328,6 +329,10 @@ class TestContextStack(unittest.TestCase): stack.register(_exit, **kwds) else: stack.register(_exit) + for wrapper in stack._callbacks: + self.assertEqual(wrapper.__name__, _exit.__name__) + self.assertEqual(wrapper.__doc__, _exit.__doc__) + self.assertEqual(result, expected) def test_register_exit(self): exc_raised = ZeroDivisionError From 8e373d228e666f59fe755412489a8d35c1cb0f9c Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 3 Jan 2012 15:05:55 +1000 Subject: [PATCH 14/28] Issue #1: Add ContextStack.preserve() --- NEWS.rst | 2 ++ contextlib2.py | 9 ++++++++- docs/index.rst | 31 +++++++++++++++++++++++++------ test_contextlib2.py | 14 +++++++++++++- 4 files changed, 48 insertions(+), 8 deletions(-) diff --git a/NEWS.rst b/NEWS.rst index dbb3c98..7ff5ef6 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -5,6 +5,8 @@ Release History 0.3 (2012-01-XX) ~~~~~~~~~~~~~~~~ +* Issue #1: Add ContextStack.preserve() to move all registered callbacks to + a new ContextStack object * Wrapped callbacks now use functools.wraps 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) diff --git a/contextlib2.py b/contextlib2.py index 65dd434..6dbd7ce 100644 --- a/contextlib2.py +++ b/contextlib2.py @@ -143,7 +143,7 @@ class closing(object): # Inspired by discussions on http://bugs.python.org/issue13585 class ContextStack(object): - """Context manager for programmatic management of resource cleanup + """Context manager for dynamic management of a stack of exit callbacks For example: @@ -156,6 +156,13 @@ class ContextStack(object): """ def __init__(self): self._callbacks = deque() + + def preserve(self): + """Preserve the context stack by transferring it to a new instance""" + new_stack = type(self)() + new_stack._callbacks = self._callbacks + self._callbacks = deque() + return new_stack def register_exit(self, callback): """Registers a callback with the standard __exit__ method signature diff --git a/docs/index.rst b/docs/index.rst index dc89fe6..91daf82 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -207,14 +207,14 @@ API Reference # the with statement, even if attempts to open files later # in the list throw an exception - Each instance maintains a stack of registered callbacks (usually context - manager exit methods) that are called in reverse order when the instance - is closed (either explicitly or implicitly at the end of a ``with`` - statement). + 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 ``with`` statement). Note that callbacks are *not* invoked + implicitly when the context stack instance is garbage collected. Since registered callbacks are invoked in the reverse order of registration, this ends up behaving as if multiple nested ``with`` - statements had been used with the registered set of resources. This even + 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. @@ -245,9 +245,28 @@ API Reference Unlike the other methods, callbacks added this way cannot suppress exceptions (as they are never passed the exception details). + .. method:: preserve() + + Transfers the callback stack to a fresh 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). + + For example, a group of files can be opened as an "all or nothing" + operation as follows:: + + with ContextStack() as stack: + files = [stack.enter_context(open(fname)) for fname in filenames] + close_files = stack.preserve().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 + + .. versionadded:: 0.3 + .. method:: close() - Immediately unwinds the context stack, invoking callbacks in the + 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. diff --git a/test_contextlib2.py b/test_contextlib2.py index 7a3150b..db1caa2 100755 --- a/test_contextlib2.py +++ b/test_contextlib2.py @@ -370,14 +370,26 @@ class TestContextStack(unittest.TestCase): def test_close(self): result = [] with ContextStack() as stack: - @stack.register # Registered first => cleaned up last + @stack.register def _exit(): result.append(1) stack.close() result.append(2) self.assertEqual(result, [1, 2]) + def test_preserve(self): + result = [] + with ContextStack() as stack: + @stack.register + def _exit(): + result.append(3) + new_stack = stack.preserve() + result.append(1) + result.append(2) + new_stack.close() + self.assertEqual(result, [1, 2, 3]) + if __name__ == "__main__": import unittest unittest.main(__name__) From 580d9bde76c4e93d1c5cecc491cd06954715d3b5 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 3 Jan 2012 22:21:27 +1000 Subject: [PATCH 15/28] Issue #3: Accept context managers in ContextStack.register_exit() --- NEWS.rst | 4 ++++ contextlib2.py | 9 ++++++++- docs/index.rst | 5 +++++ test_contextlib2.py | 9 +++++++++ 4 files changed, 26 insertions(+), 1 deletion(-) diff --git a/NEWS.rst b/NEWS.rst index 7ff5ef6..4834488 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -5,18 +5,22 @@ Release History 0.3 (2012-01-XX) ~~~~~~~~~~~~~~~~ +* Issue #3: ContextStack.register_exit() now accepts objects with __exit__ + attributes in addition to accepting exit callbacks directly * Issue #1: Add ContextStack.preserve() to move all registered callbacks to a new ContextStack object * Wrapped callbacks now use functools.wraps 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) ~~~~~~~~~~~~~~~~ diff --git a/contextlib2.py b/contextlib2.py index 6dbd7ce..2b95040 100644 --- a/contextlib2.py +++ b/contextlib2.py @@ -168,8 +168,15 @@ class ContextStack(object): """Registers a callback with the standard __exit__ method signature Can suppress exceptions the same way __exit__ methods can. + + Also accepts any object with an __exit__ method (registering the + method instead of the object itself) """ - self._callbacks.append(callback) + try: + exit = callback.__exit__ + except AttributeError: + exit = callback + self._callbacks.append(exit) return callback # Allow use as a decorator def register(self, callback, *args, **kwds): diff --git a/docs/index.rst b/docs/index.rst index 91daf82..b0111c3 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -237,6 +237,11 @@ API Reference By returning true values, these callbacks can suppress exceptions the same way context manager :meth:`__exit__` methods can. + This method also accepts any object with an ``__exit__`` method, and + will register that method as the callback. This is mainly useful to + cover part of an :meth:`__enter__` implementation with a context + manager's own :meth:`__exit__` method. + .. method:: register(callback, *args, **kwds) Accepts an arbitrary callback function and arguments and adds it to diff --git a/test_contextlib2.py b/test_contextlib2.py index db1caa2..31b95b0 100755 --- a/test_contextlib2.py +++ b/test_contextlib2.py @@ -344,9 +344,18 @@ class TestContextStack(unittest.TestCase): 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 ContextStack() as stack: stack.register_exit(_expect_ok) + stack.register_exit(ExitCM(_expect_ok)) stack.register_exit(_suppress_exc) + stack.register_exit(ExitCM(_expect_exc)) stack.register_exit(_expect_exc) stack.register_exit(_expect_exc) 1/0 From 7cab096ee8aed5f7b17cb3154dbfec8e150907e9 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 3 Jan 2012 23:53:22 +1000 Subject: [PATCH 16/28] Issue #2: Add examples and recipes section to docs --- NEWS.rst | 1 + docs/index.rst | 167 ++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 167 insertions(+), 1 deletion(-) diff --git a/NEWS.rst b/NEWS.rst index 4834488..f25f0a6 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -5,6 +5,7 @@ Release History 0.3 (2012-01-XX) ~~~~~~~~~~~~~~~~ +* Issue #2: Add examples and recipes section to docs * Issue #3: ContextStack.register_exit() now accepts objects with __exit__ attributes in addition to accepting exit callbacks directly * Issue #1: Add ContextStack.preserve() to move all registered callbacks to diff --git a/docs/index.rst b/docs/index.rst index b0111c3..9c8a64b 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -33,7 +33,7 @@ are currently: API Reference ============= -.. function:: @contextmanager +.. function:: contextmanager This function is a decorator that can be used to define a factory function for ``with`` statement context managers, without needing to @@ -280,6 +280,171 @@ API Reference New API for :mod:`contextlib2`, not available in standard library +Examples and Recipes +==================== + +This section describes some examples and recipes for making effective use of +the tools provided by :mod:`contextlib2`. Some of them may also work with +:mod:`contextlib` in sufficiently recent versions of Python. When this is the +case, it is noted at the end of the example. + + +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. The +:meth:`ContextDecorator.refresh_cm` method even makes it possible to use +otherwise single use context managers (such as those created by +:func:`contextmanager`) that way. + +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, +:func:`contextmanager` provides both capabilities in a single +definition:: + + from contextlib2 import contextmanager + import logging + + logging.basicConfig(level=logging.INFO) + + @contextmanager + def track_entry_and_exit(name): + logging.info('Entering: {}'.format(name)) + yield + logging.info('Exiting: {}'.format(name)) + +This 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. + +This example should also work with :mod:`contextlib` in Python 3.2.1 or later. + + +Cleaning up in an ``__enter__`` implementation +---------------------------------------------- + +As noted in the documentation of :meth:`ContextStack.register_exit`, 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 contextlib2 import ContextStack + + class ResourceManager(object): + + def __init__(self, acquire_resource, release_resource, check_resource_ok=None): + self.acquire_resource = acquire_resource + self.release_resource = release_resource + self.check_resource_ok = check_resource_ok + + def __enter__(self): + resource = self.acquire_resource() + if self.check_resource_ok is not None: + with ContextStack() as stack: + stack.register_exit(self) + if not self.check_resource_ok(resource): + msg = "Failed validation for {!r}" + raise RuntimeError(msg.format(resource)) + # 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.preserve() + 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:`ContextStack` 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 contextlib2 import ContextStack + + with ContextStack() as stack: + stack.register(cleanup_resources) + result = perform_operation() + if result: + stack.preserve() + +This allows the intended cleanup up behaviour to be made explicit up front, +rather than requiring a separate flag variable. + +If you find yourself using this pattern a lot, it can be simplified even +further by means of a small helper class:: + + from contextlib2 import ContextStack + + class Callback(ContextStack): + def __init__(self, callback, *args, **kwds): + super(Callback, self).__init__() + self.register(callback, *args, **kwds) + + def cancel(self): + self.preserve() + + 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:`ContextStack.register_exit` to declare the resource cleanup in +advance:: + + from contextlib2 import ContextStack + + with ContextStack() as stack: + @stack.register_exit + def cleanup_resources(*exc_details): + ... + result = perform_operation() + if result: + stack.preserve() + + Obtaining the Module ==================== From 8bca9f8cd017a6ad180e78bf6edbfe62b097dc11 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 3 Jan 2012 23:58:00 +1000 Subject: [PATCH 17/28] Issue #5: ContextStack.register no longer pointlessly returns the wrapped function --- NEWS.rst | 2 ++ contextlib2.py | 2 +- test_contextlib2.py | 8 ++++---- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/NEWS.rst b/NEWS.rst index f25f0a6..fd3cde5 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -5,6 +5,8 @@ Release History 0.3 (2012-01-XX) ~~~~~~~~~~~~~~~~ +* Issue #5: ContextStack.register no longer pointlessly returns the wrapped + function * Issue #2: Add examples and recipes section to docs * Issue #3: ContextStack.register_exit() now accepts objects with __exit__ attributes in addition to accepting exit callbacks directly diff --git a/contextlib2.py b/contextlib2.py index 2b95040..a9c24a3 100644 --- a/contextlib2.py +++ b/contextlib2.py @@ -187,7 +187,7 @@ class ContextStack(object): @wraps(callback) def _wrapper(exc_type, exc, tb): callback(*args, **kwds) - return self.register_exit(_wrapper) + self.register_exit(_wrapper) def enter_context(self, cm): """Enters the supplied context manager diff --git a/test_contextlib2.py b/test_contextlib2.py index 31b95b0..8ee7bdb 100755 --- a/test_contextlib2.py +++ b/test_contextlib2.py @@ -322,13 +322,13 @@ class TestContextStack(unittest.TestCase): with ContextStack() as stack: for args, kwds in reversed(expected): if args and kwds: - stack.register(_exit, *args, **kwds) + self.assertIsNone(stack.register(_exit, *args, **kwds)) elif args: - stack.register(_exit, *args) + self.assertIsNone(stack.register(_exit, *args)) elif kwds: - stack.register(_exit, **kwds) + self.assertIsNone(stack.register(_exit, **kwds)) else: - stack.register(_exit) + self.assertIsNone(stack.register(_exit)) for wrapper in stack._callbacks: self.assertEqual(wrapper.__name__, _exit.__name__) self.assertEqual(wrapper.__doc__, _exit.__doc__) From 0cbb244909322fc9a49b84af2c50d6e98b32054c Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Wed, 4 Jan 2012 00:26:17 +1000 Subject: [PATCH 18/28] Issue #6: fix various problems related to the callback wrappers, including correctly looking up __exit__ on the type in register_exit() --- NEWS.rst | 3 ++- contextlib2.py | 27 ++++++++++++++++++--------- test_contextlib2.py | 29 ++++++++++++++++++++++++----- 3 files changed, 44 insertions(+), 15 deletions(-) diff --git a/NEWS.rst b/NEWS.rst index fd3cde5..d8a972d 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -12,7 +12,8 @@ Release History attributes in addition to accepting exit callbacks directly * Issue #1: Add ContextStack.preserve() to move all registered callbacks to a new ContextStack object -* Wrapped callbacks now use functools.wraps to aid in introspection +* 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) diff --git a/contextlib2.py b/contextlib2.py index a9c24a3..6d408b1 100644 --- a/contextlib2.py +++ b/contextlib2.py @@ -164,6 +164,13 @@ class ContextStack(object): self._callbacks = deque() return new_stack + def _register_cm_exit(self, cm, cm_exit): + """Helper to correctly register callbacks to __exit__ methods""" + def _exit_wrapper(*exc_details): + return cm_exit(cm, *exc_details) + _exit_wrapper.__self__ = cm + self.register_exit(_exit_wrapper) + def register_exit(self, callback): """Registers a callback with the standard __exit__ method signature @@ -172,11 +179,13 @@ class ContextStack(object): Also accepts any object with an __exit__ method (registering the method instead of the object itself) """ + _cb_type = type(callback) try: - exit = callback.__exit__ + exit = _cb_type.__exit__ except AttributeError: - exit = callback - self._callbacks.append(exit) + self._callbacks.append(callback) + else: + self._register_cm_exit(callback, exit) return callback # Allow use as a decorator def register(self, callback, *args, **kwds): @@ -184,10 +193,12 @@ class ContextStack(object): Cannot suppress exceptions. """ - @wraps(callback) - def _wrapper(exc_type, exc, tb): + def _exit_wrapper(exc_type, exc, tb): callback(*args, **kwds) - self.register_exit(_wrapper) + # We changed the signature, so using @wraps is not appropriate, but + # setting __wrapped__ may still help with introspection + _exit_wrapper.__wrapped__ = callback + self.register_exit(_exit_wrapper) def enter_context(self, cm): """Enters the supplied context manager @@ -199,9 +210,7 @@ class ContextStack(object): _cm_type = type(cm) _exit = _cm_type.__exit__ result = _cm_type.__enter__(cm) - def _exit_wrapper(*exc_details): - return _exit(cm, *exc_details) - self.register_exit(_exit_wrapper) + self._register_cm_exit(cm, _exit) return result def close(self): diff --git a/test_contextlib2.py b/test_contextlib2.py index 8ee7bdb..f83f217 100755 --- a/test_contextlib2.py +++ b/test_contextlib2.py @@ -330,8 +330,9 @@ class TestContextStack(unittest.TestCase): else: self.assertIsNone(stack.register(_exit)) for wrapper in stack._callbacks: - self.assertEqual(wrapper.__name__, _exit.__name__) - self.assertEqual(wrapper.__doc__, _exit.__doc__) + self.assertIs(wrapper.__wrapped__, _exit) + self.assertNotEqual(wrapper.__name__, _exit.__name__) + self.assertIsNone(wrapper.__doc__, _exit.__doc__) self.assertEqual(result, expected) def test_register_exit(self): @@ -353,11 +354,19 @@ class TestContextStack(unittest.TestCase): self.check_exc(*exc_details) with ContextStack() as stack: stack.register_exit(_expect_ok) - stack.register_exit(ExitCM(_expect_ok)) + self.assertIs(stack._callbacks[-1], _expect_ok) + cm = ExitCM(_expect_ok) + stack.register_exit(cm) + self.assertIs(stack._callbacks[-1].__self__, cm) stack.register_exit(_suppress_exc) - stack.register_exit(ExitCM(_expect_exc)) + self.assertIs(stack._callbacks[-1], _suppress_exc) + cm = ExitCM(_expect_exc) + stack.register_exit(cm) + self.assertIs(stack._callbacks[-1].__self__, cm) stack.register_exit(_expect_exc) + self.assertIs(stack._callbacks[-1], _expect_exc) stack.register_exit(_expect_exc) + self.assertIs(stack._callbacks[-1], _expect_exc) 1/0 def test_enter_context(self): @@ -368,11 +377,13 @@ class TestContextStack(unittest.TestCase): result.append(3) result = [] + cm = TestCM() with ContextStack() as stack: @stack.register # Registered first => cleaned up last def _exit(): result.append(4) - stack.enter_context(TestCM()) + stack.enter_context(cm) + self.assertIs(stack._callbacks[-1].__self__, cm) result.append(2) self.assertEqual(result, [1, 2, 3, 4]) @@ -398,6 +409,14 @@ class TestContextStack(unittest.TestCase): new_stack.close() self.assertEqual(result, [1, 2, 3]) + def test_instance_bypass(self): + class Example(object): pass + cm = Example() + cm.__exit__ = object() + stack = ContextStack() + self.assertRaises(AttributeError, stack.enter_context, cm) + stack.register_exit(cm) + self.assertIs(stack._callbacks[-1], cm) if __name__ == "__main__": import unittest From e2b0e0c0372cfb0a137062e3b674a8706a014da3 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Wed, 4 Jan 2012 14:31:43 +1000 Subject: [PATCH 19/28] Prep for 0.3 release --- NEWS.rst | 4 ++-- VERSION.txt | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/NEWS.rst b/NEWS.rst index d8a972d..3715fd6 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -2,7 +2,7 @@ Release History --------------- -0.3 (2012-01-XX) +0.3 (2012-01-04) ~~~~~~~~~~~~~~~~ * Issue #5: ContextStack.register no longer pointlessly returns the wrapped @@ -13,7 +13,7 @@ Release History * 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 + (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) diff --git a/VERSION.txt b/VERSION.txt index f46a2c2..1d71ef9 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1 +1 @@ -0.2+ \ No newline at end of file +0.3 \ No newline at end of file From 4e0cbce114d0586f820b040b866280cc5b63a6ed Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 17 Jan 2012 21:57:24 +1000 Subject: [PATCH 20/28] Issue #7: Provide MANIFEST.in to ensure files are uploaded correctly --- MANIFEST.in | 3 +++ NEWS.rst | 4 ++++ VERSION.txt | 2 +- 3 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 MANIFEST.in diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..9e664ba --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,3 @@ +include *.py *.txt *.rst +recursive-include docs *.rst *.py make.bat Makefile + diff --git a/NEWS.rst b/NEWS.rst index 3715fd6..945a7d4 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -1,6 +1,10 @@ Release History --------------- +0.3.1 (2012-01-17) +~~~~~~~~~~~~~~~~~~ + +* Issue #7: Add MANIFEST.in so PyPI package contains all relevant files 0.3 (2012-01-04) ~~~~~~~~~~~~~~~~ diff --git a/VERSION.txt b/VERSION.txt index 1d71ef9..a2268e2 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1 +1 @@ -0.3 \ No newline at end of file +0.3.1 \ No newline at end of file From bccd39fa3a341be8c35290c2e304d4b27ac70a64 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 1 May 2012 20:06:25 +1000 Subject: [PATCH 21/28] Create development branch and start work on 0.4.0 --- NEWS.rst | 7 +++++++ VERSION.txt | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/NEWS.rst b/NEWS.rst index 945a7d4..d8b3e5e 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -1,11 +1,18 @@ Release History --------------- +0.4.0 (2012-05-??) +~~~~~~~~~~~~~~~~~~ + +* TBD + + 0.3.1 (2012-01-17) ~~~~~~~~~~~~~~~~~~ * Issue #7: Add MANIFEST.in so PyPI package contains all relevant files + 0.3 (2012-01-04) ~~~~~~~~~~~~~~~~ diff --git a/VERSION.txt b/VERSION.txt index a2268e2..60a2d3e 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1 +1 @@ -0.3.1 \ No newline at end of file +0.4.0 \ No newline at end of file From 7d3f886c77a5d2b55b97ab7ef233f340bc5a464e Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 1 May 2012 20:42:19 +1000 Subject: [PATCH 22/28] Fallback to unittest2 when necessary --- NEWS.rst | 2 +- setup.py | 3 +++ test_contextlib2.py | 5 ++++- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/NEWS.rst b/NEWS.rst index d8b3e5e..8553b0a 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -4,7 +4,7 @@ Release History 0.4.0 (2012-05-??) ~~~~~~~~~~~~~~~~~~ -* TBD +* Fall back to unittest2 if unittest is missing required functionality 0.3.1 (2012-01-17) diff --git a/setup.py b/setup.py index 1544eef..0c897f4 100755 --- a/setup.py +++ b/setup.py @@ -1,6 +1,9 @@ #!/usr/bin/env python from distutils.core import setup +# Technically, unittest2 is a dependency to run the tests on 2.6 and 3.1 +# Not sure how best to express that cleanly here + setup( name='contextlib2', version=open('VERSION.txt').read().strip(), diff --git a/test_contextlib2.py b/test_contextlib2.py index f83f217..c4bb09b 100755 --- a/test_contextlib2.py +++ b/test_contextlib2.py @@ -1,8 +1,11 @@ #!/usr/bin/env python -"""Unit tests for contextlib.py, and other context managers.""" +"""Unit tests for contextlib2""" import sys + import unittest +if not hasattr(unittest, "skipIf"): + import unittest2 as unittest from contextlib2 import * # Tests __all__ From 141ca2353f1b495f3ab854b8b119a8bc5ebf7f22 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 1 May 2012 21:09:21 +1000 Subject: [PATCH 23/28] Update comment - I do know how to express it, I just don't want the external dependency --- setup.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 0c897f4..b172c59 100755 --- a/setup.py +++ b/setup.py @@ -2,7 +2,8 @@ from distutils.core import setup # Technically, unittest2 is a dependency to run the tests on 2.6 and 3.1 -# Not sure how best to express that cleanly here +# This file ignores that, since I don't want to depend on distribute +# or setuptools just to get "tests_require" support setup( name='contextlib2', From 21a5d8b0a4d0a4cbf6d96f50a57eb57bf94be506 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 1 May 2012 21:50:17 +1000 Subject: [PATCH 24/28] Issue #8: Switch to ExitStack instead of ContextStack --- NEWS.rst | 2 + contextlib2.py | 64 +++++++++++------- docs/index.rst | 74 ++++++++++++--------- test_contextlib2.py | 153 ++++++++++++++++++++++++++++++++++++++++---- 4 files changed, 227 insertions(+), 66 deletions(-) diff --git a/NEWS.rst b/NEWS.rst index 8553b0a..0d4d8ee 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -4,6 +4,8 @@ Release History 0.4.0 (2012-05-??) ~~~~~~~~~~~~~~~~~~ +* Issue #8: Replace ContextStack with ExitStack (old ContextStack API + retained for backwards compatibility) * Fall back to unittest2 if unittest is missing required functionality diff --git a/contextlib2.py b/contextlib2.py index 6d408b1..1fe5bc2 100644 --- a/contextlib2.py +++ b/contextlib2.py @@ -4,7 +4,8 @@ import sys from collections import deque from functools import wraps -__all__ = ["contextmanager", "closing", "ContextDecorator", "ContextStack"] +__all__ = ["contextmanager", "closing", "ContextDecorator", + "ContextStack", "ExitStack"] class ContextDecorator(object): @@ -142,12 +143,12 @@ class closing(object): # Inspired by discussions on http://bugs.python.org/issue13585 -class ContextStack(object): +class ExitStack(object): """Context manager for dynamic management of a stack of exit callbacks For example: - with ContextStack() as stack: + 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 @@ -155,23 +156,23 @@ class ContextStack(object): """ def __init__(self): - self._callbacks = deque() + self._exit_callbacks = deque() - def preserve(self): + def pop_all(self): """Preserve the context stack by transferring it to a new instance""" new_stack = type(self)() - new_stack._callbacks = self._callbacks - self._callbacks = deque() + new_stack._exit_callbacks = self._exit_callbacks + self._exit_callbacks = deque() return new_stack - def _register_cm_exit(self, cm, cm_exit): + def _push_cm_exit(self, cm, cm_exit): """Helper to correctly register callbacks to __exit__ methods""" def _exit_wrapper(*exc_details): return cm_exit(cm, *exc_details) _exit_wrapper.__self__ = cm - self.register_exit(_exit_wrapper) + self.push(_exit_wrapper) - def register_exit(self, callback): + def push(self, exit): """Registers a callback with the standard __exit__ method signature Can suppress exceptions the same way __exit__ methods can. @@ -179,16 +180,19 @@ class ContextStack(object): Also accepts any object with an __exit__ method (registering the method instead of the object itself) """ - _cb_type = type(callback) + # 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 = _cb_type.__exit__ + exit_method = _cb_type.__exit__ except AttributeError: - self._callbacks.append(callback) + # Not a context manager, so assume its a callable + self._exit_callbacks.append(exit) else: - self._register_cm_exit(callback, exit) - return callback # Allow use as a decorator + self._push_cm_exit(exit, exit_method) + return exit # Allow use as a decorator - def register(self, callback, *args, **kwds): + def callback(self, callback, *args, **kwds): """Registers an arbitrary callback and arguments. Cannot suppress exceptions. @@ -198,19 +202,20 @@ class ContextStack(object): # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection _exit_wrapper.__wrapped__ = callback - self.register_exit(_exit_wrapper) + self.push(_exit_wrapper) + return callback # Allow use as a decorator def enter_context(self, cm): """Enters the supplied context manager - If successful, also registers its __exit__ method as a callback and + 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._register_cm_exit(cm, _exit) + self._push_cm_exit(cm, _exit) return result def close(self): @@ -221,7 +226,7 @@ class ContextStack(object): return self def __exit__(self, *exc_details): - if not self._callbacks: + if not self._exit_callbacks: return # This looks complicated, but it is really just # setting up a chain of try-expect statements to ensure @@ -230,8 +235,8 @@ class ContextStack(object): def _invoke_next_callback(exc_details): # Callbacks are removed from the list in FIFO order # but the recursion means they're invoked in LIFO order - cb = self._callbacks.popleft() - if not self._callbacks: + cb = self._exit_callbacks.popleft() + if not self._exit_callbacks: # Innermost callback is invoked directly return cb(*exc_details) # More callbacks left, so descend another level in the stack @@ -249,4 +254,17 @@ class ContextStack(object): suppress_exc = cb(*exc_details) or suppress_exc return suppress_exc # Kick off the recursive chain - return _invoke_next_callback(exc_details) \ No newline at end of file + return _invoke_next_callback(exc_details) + +# Preserve backwards compatibility +class ContextStack(ExitStack): + """Backwards compatibility alias for ExitStack""" + + 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() diff --git a/docs/index.rst b/docs/index.rst index 9c8a64b..f4ea3ce 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -26,7 +26,7 @@ This module is primarily a backport of the Python 3.2 version of for new features not yet part of the standard library. Those new features are currently: -* :class:`ContextStack` +* :class:`ExitStack` * :meth:`ContextDecorator.refresh_cm` @@ -192,7 +192,7 @@ API Reference Made the standard library's private :meth:`refresh_cm` API public -.. class:: ContextStack() +.. class:: ExitStack() A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those @@ -201,7 +201,7 @@ API Reference For example, a set of files may easily be handled in a single with statement as follows:: - with ContextStack() as stack: + 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 @@ -228,7 +228,7 @@ API Reference These context managers may suppress exceptions just as they normally would if used directly as part of a ``with`` statement. - .. method:: register_exit(callback) + .. method:: push(exit) Directly accepts a callback with the same signature as a context manager's :meth:`__exit__` method and adds it to the callback @@ -242,7 +242,7 @@ API Reference cover part of an :meth:`__enter__` implementation with a context manager's own :meth:`__exit__` method. - .. method:: register(callback, *args, **kwds) + .. method:: callback(callback, *args, **kwds) Accepts an arbitrary callback function and arguments and adds it to the callback stack. @@ -250,7 +250,7 @@ API Reference Unlike the other methods, callbacks added this way cannot suppress exceptions (as they are never passed the exception details). - .. method:: preserve() + .. method:: pop_all() Transfers the callback stack to a fresh instance and returns it. No callbacks are invoked by this operation - instead, they will now be @@ -259,16 +259,14 @@ API Reference For example, a group of files can be opened as an "all or nothing" operation as follows:: - with ContextStack() as stack: + with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in filenames] - close_files = stack.preserve().close + 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 - .. versionadded:: 0.3 - .. method:: close() Immediately unwinds the callback stack, invoking callbacks in the @@ -276,6 +274,18 @@ API Reference callbacks registered, the arguments passed in will indicate that no exception occurred. + .. versionadded:: 0.4 + New API for :mod:`contextlib2`, not available in standard library + + +.. class:: ContextStack() + + An earlier incarnation of the :class:`ExitStack` interface. This class + is deprecated and should no longer be used. + + .. versionchanged:: 0.4 + Deprecated in favour of :class:`ExitStack` + .. versionadded:: 0.2 New API for :mod:`contextlib2`, not available in standard library @@ -339,7 +349,7 @@ This example should also work with :mod:`contextlib` in Python 3.2.1 or later. Cleaning up in an ``__enter__`` implementation ---------------------------------------------- -As noted in the documentation of :meth:`ContextStack.register_exit`, this +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. @@ -347,7 +357,7 @@ 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 contextlib2 import ContextStack + from contextlib2 import ExitStack class ResourceManager(object): @@ -359,15 +369,15 @@ and maps them to the context management protocol:: def __enter__(self): resource = self.acquire_resource() if self.check_resource_ok is not None: - with ContextStack() as stack: - stack.register_exit(self) + with ExitStack() as stack: + stack.push(self) if not self.check_resource_ok(resource): msg = "Failed validation for {!r}" raise RuntimeError(msg.format(resource)) # 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.preserve() + stack.pop_all() return resource def __exit__(self, *exc_details): @@ -396,17 +406,17 @@ 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:`ContextStack` makes it possible to instead register a callback for +: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 contextlib2 import ContextStack + from contextlib2 import ExitStack - with ContextStack() as stack: - stack.register(cleanup_resources) + with ExitStack() as stack: + stack.callback(cleanup_resources) result = perform_operation() if result: - stack.preserve() + stack.pop_all() This allows the intended cleanup up behaviour to be made explicit up front, rather than requiring a separate flag variable. @@ -414,15 +424,15 @@ rather than requiring a separate flag variable. If you find yourself using this pattern a lot, it can be simplified even further by means of a small helper class:: - from contextlib2 import ContextStack + from contextlib2 import ExitStack - class Callback(ContextStack): + class Callback(ExitStack): def __init__(self, callback, *args, **kwds): super(Callback, self).__init__() - self.register(callback, *args, **kwds) + self.callback(callback, *args, **kwds) def cancel(self): - self.preserve() + self.pop_all() with Callback(cleanup_resources) as cb: result = perform_operation() @@ -431,18 +441,22 @@ further by means of a small helper class:: 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:`ContextStack.register_exit` to declare the resource cleanup in +:meth:`ExitStack.callback` to declare the resource cleanup in advance:: - from contextlib2 import ContextStack + from contextlib2 import ExitStack - with ContextStack() as stack: - @stack.register_exit - def cleanup_resources(*exc_details): + with ExitStack() as stack: + @stack.callback + def cleanup_resources(): ... result = perform_operation() if result: - stack.preserve() + 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 Obtaining the Module diff --git a/test_contextlib2.py b/test_contextlib2.py index c4bb09b..86cf15e 100755 --- a/test_contextlib2.py +++ b/test_contextlib2.py @@ -303,6 +303,129 @@ class TestContextDecorator(unittest.TestCase): self.assertEqual(state, [1, 'something else', 999]) +class TestExitStack(unittest.TestCase): + + def test_no_resources(self): + with ExitStack(): + pass + + def test_callback(self): + expected = [ + ((), {}), + ((1,), {}), + ((1,2), {}), + ((), dict(example=1)), + ((1,), dict(example=1)), + ((1,2), dict(example=1)), + ] + result = [] + def _exit(*args, **kwds): + """Test metadata propagation""" + result.append((args, kwds)) + with ExitStack() 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.__wrapped__, _exit) + self.assertNotEqual(wrapper.__name__, _exit.__name__) + self.assertIsNone(wrapper.__doc__, _exit.__doc__) + self.assertEqual(result, expected) + + 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 ExitStack() as stack: + stack.push(_expect_ok) + self.assertIs(stack._exit_callbacks[-1], _expect_ok) + cm = ExitCM(_expect_ok) + stack.push(cm) + self.assertIs(stack._exit_callbacks[-1].__self__, cm) + stack.push(_suppress_exc) + self.assertIs(stack._exit_callbacks[-1], _suppress_exc) + cm = ExitCM(_expect_exc) + stack.push(cm) + self.assertIs(stack._exit_callbacks[-1].__self__, cm) + stack.push(_expect_exc) + self.assertIs(stack._exit_callbacks[-1], _expect_exc) + stack.push(_expect_exc) + self.assertIs(stack._exit_callbacks[-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 ExitStack() 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].__self__, cm) + result.append(2) + self.assertEqual(result, [1, 2, 3, 4]) + + def test_close(self): + result = [] + with ExitStack() 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 ExitStack() 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_instance_bypass(self): + class Example(object): pass + cm = Example() + cm.__exit__ = object() + stack = ExitStack() + self.assertRaises(AttributeError, stack.enter_context, cm) + stack.push(cm) + self.assertIs(stack._exit_callbacks[-1], cm) + + class TestContextStack(unittest.TestCase): def test_no_resources(self): @@ -325,14 +448,15 @@ class TestContextStack(unittest.TestCase): with ContextStack() as stack: for args, kwds in reversed(expected): if args and kwds: - self.assertIsNone(stack.register(_exit, *args, **kwds)) + f = stack.register(_exit, *args, **kwds) elif args: - self.assertIsNone(stack.register(_exit, *args)) + f = stack.register(_exit, *args) elif kwds: - self.assertIsNone(stack.register(_exit, **kwds)) + f = stack.register(_exit, **kwds) else: - self.assertIsNone(stack.register(_exit)) - for wrapper in stack._callbacks: + f = stack.register(_exit) + self.assertIs(f, _exit) + for wrapper in stack._exit_callbacks: self.assertIs(wrapper.__wrapped__, _exit) self.assertNotEqual(wrapper.__name__, _exit.__name__) self.assertIsNone(wrapper.__doc__, _exit.__doc__) @@ -357,19 +481,19 @@ class TestContextStack(unittest.TestCase): self.check_exc(*exc_details) with ContextStack() as stack: stack.register_exit(_expect_ok) - self.assertIs(stack._callbacks[-1], _expect_ok) + self.assertIs(stack._exit_callbacks[-1], _expect_ok) cm = ExitCM(_expect_ok) stack.register_exit(cm) - self.assertIs(stack._callbacks[-1].__self__, cm) + self.assertIs(stack._exit_callbacks[-1].__self__, cm) stack.register_exit(_suppress_exc) - self.assertIs(stack._callbacks[-1], _suppress_exc) + self.assertIs(stack._exit_callbacks[-1], _suppress_exc) cm = ExitCM(_expect_exc) stack.register_exit(cm) - self.assertIs(stack._callbacks[-1].__self__, cm) + self.assertIs(stack._exit_callbacks[-1].__self__, cm) stack.register_exit(_expect_exc) - self.assertIs(stack._callbacks[-1], _expect_exc) + self.assertIs(stack._exit_callbacks[-1], _expect_exc) stack.register_exit(_expect_exc) - self.assertIs(stack._callbacks[-1], _expect_exc) + self.assertIs(stack._exit_callbacks[-1], _expect_exc) 1/0 def test_enter_context(self): @@ -385,8 +509,9 @@ class TestContextStack(unittest.TestCase): @stack.register # Registered first => cleaned up last def _exit(): result.append(4) + self.assertIsNotNone(_exit) stack.enter_context(cm) - self.assertIs(stack._callbacks[-1].__self__, cm) + self.assertIs(stack._exit_callbacks[-1].__self__, cm) result.append(2) self.assertEqual(result, [1, 2, 3, 4]) @@ -396,6 +521,7 @@ class TestContextStack(unittest.TestCase): @stack.register def _exit(): result.append(1) + self.assertIsNotNone(_exit) stack.close() result.append(2) self.assertEqual(result, [1, 2]) @@ -406,6 +532,7 @@ class TestContextStack(unittest.TestCase): @stack.register def _exit(): result.append(3) + self.assertIsNotNone(_exit) new_stack = stack.preserve() result.append(1) result.append(2) @@ -419,7 +546,7 @@ class TestContextStack(unittest.TestCase): stack = ContextStack() self.assertRaises(AttributeError, stack.enter_context, cm) stack.register_exit(cm) - self.assertIs(stack._callbacks[-1], cm) + self.assertIs(stack._exit_callbacks[-1], cm) if __name__ == "__main__": import unittest From a64f375bc56d5e9f2aa76ef27efa65fcc4db16b0 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Mon, 14 Sep 2015 14:34:31 +0000 Subject: [PATCH 25/28] Add development notes to README --- README.txt | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.txt b/README.txt index 3bf4588..bbab787 100644 --- a/README.txt +++ b/README.txt @@ -1,3 +1,15 @@ contextlib2 is a backport of the standard library's contextlib module to earlier Python versions. It also serves as a real world proving ground for possible future enhancements to the standard library version. + +Development +----------- + +contextlib2 currently has no dependencies. + +Local testing is currently just a matter of running "python test_contextlib2.py" + +Continuous integration +---------------------- + +CI is set up in Codeship to run against PRs and commits. From ca20b96805f47fa13aa24deaedfc433f170b3985 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Tue, 15 Sep 2015 00:37:30 +1000 Subject: [PATCH 26/28] Close branch ncoghlan/add-dev-notes-to-readme-1442241260952 From a81d62580df5e44b7311ee693cc1231c858b5017 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Mon, 14 Sep 2015 14:50:29 +0000 Subject: [PATCH 27/28] Add Codeship status indicator --- README.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.txt b/README.txt index bbab787..2762fe5 100644 --- a/README.txt +++ b/README.txt @@ -13,3 +13,5 @@ Continuous integration ---------------------- CI is set up in Codeship to run against PRs and commits. + +[![Codeship Status for ncoghlan/contextlib2](https://codeship.com/projects/884e9500-3d1a-0133-3eb0-1abe7f570a4c/status?branch=default)](https://codeship.com/projects/102388) From b28f20d15736271b9c50d43ceccb3c3108464b04 Mon Sep 17 00:00:00 2001 From: Nick Coghlan <@ncoghlan> Date: Mon, 14 Sep 2015 14:51:11 +0000 Subject: [PATCH 28/28] Indicate README format in extension --- README.txt => README.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename README.txt => README.md (100%) diff --git a/README.txt b/README.md similarity index 100% rename from README.txt rename to README.md