[Python-checkins] cpython: Issue #15806: Add contextlib.ignored().

raymond.hettinger python-checkins at python.org
Mon Mar 11 06:27:07 CET 2013


http://hg.python.org/cpython/rev/406b47c64480
changeset:   82598:406b47c64480
user:        Raymond Hettinger <python at rcn.com>
date:        Sun Mar 10 22:26:51 2013 -0700
summary:
  Issue #15806: Add contextlib.ignored().

files:
  Doc/library/contextlib.rst  |  20 ++++++++++++++++++++
  Lib/contextlib.py           |  14 +++++++++++++-
  Lib/test/test_contextlib.py |  22 ++++++++++++++++++++++
  Misc/NEWS                   |   3 +++
  4 files changed, 58 insertions(+), 1 deletions(-)


diff --git a/Doc/library/contextlib.rst b/Doc/library/contextlib.rst
--- a/Doc/library/contextlib.rst
+++ b/Doc/library/contextlib.rst
@@ -94,6 +94,26 @@
    without needing to explicitly close ``page``.  Even if an error occurs,
    ``page.close()`` will be called when the :keyword:`with` block is exited.
 
+.. function:: ignored(*exceptions)
+
+   Return a context manager that ignores the specified expections if they
+   occur in the body of a with-statement.
+
+   For example::
+
+       from contextlib import ignored
+
+       with ignored(OSError):
+           os.remove('somefile.tmp')
+
+   This code is equivalent to::
+
+       try:
+           os.remove('somefile.tmp')
+       except OSError:
+           pass
+
+   .. versionadded:: 3.4
 
 .. class:: ContextDecorator()
 
diff --git a/Lib/contextlib.py b/Lib/contextlib.py
--- a/Lib/contextlib.py
+++ b/Lib/contextlib.py
@@ -4,7 +4,7 @@
 from collections import deque
 from functools import wraps
 
-__all__ = ["contextmanager", "closing", "ContextDecorator", "ExitStack"]
+__all__ = ["contextmanager", "closing", "ContextDecorator", "ExitStack", "ignored"]
 
 
 class ContextDecorator(object):
@@ -140,6 +140,18 @@
     def __exit__(self, *exc_info):
         self.thing.close()
 
+ at contextmanager
+def ignored(*exceptions):
+    """Context manager to ignore specifed exceptions
+
+         with ignored(OSError):
+             os.remove(somefile)
+
+    """
+    try:
+        yield
+    except exceptions:
+        pass
 
 # Inspired by discussions on http://bugs.python.org/issue13585
 class ExitStack(object):
diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py
--- a/Lib/test/test_contextlib.py
+++ b/Lib/test/test_contextlib.py
@@ -594,6 +594,28 @@
         stack.push(cm)
         self.assertIs(stack._exit_callbacks[-1], cm)
 
+class TestIgnored(unittest.TestCase):
+
+    def test_no_exception(self):
+
+        with ignored(ValueError):
+            self.assertEqual(pow(2, 5), 32)
+
+    def test_exact_exception(self):
+
+        with ignored(TypeError):
+            len(5)
+
+    def test_multiple_exception_args(self):
+
+        with ignored(ZeroDivisionError, TypeError):
+            len(5)
+
+    def test_exception_hierarchy(self):
+
+        with ignored(LookupError):
+            'Hello'[50]
+
 
 # This is needed to make the test actually run under regrtest.py!
 def test_main():
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -280,6 +280,9 @@
 _ Issue #17385: Fix quadratic behavior in threading.Condition.  The FIFO
   queue now uses a deque instead of a list.
 
+- Issue #15806: Add contextlib.ignored().  This creates a context manager
+  to ignore specified exceptions, replacing the "except Exc: pass" idiom.
+
 - Issue #14645: The email generator classes now produce output using the
   specified linesep throughout.  Previously if the prolog, epilog, or
   body were stored with a different linesep, that linesep was used.  This

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list