diff options
author | Raymond Hettinger <python@rcn.com> | 2013-03-11 05:26:51 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2013-03-11 05:26:51 (GMT) |
commit | e318a883fece5d9a45165670b5f995886f524820 (patch) | |
tree | bc9a655a3d7c0636940f6decf9b1f73f5bb97856 /Lib | |
parent | c0417357d14b72763ba919728a1449373d122647 (diff) | |
download | cpython-e318a883fece5d9a45165670b5f995886f524820.zip cpython-e318a883fece5d9a45165670b5f995886f524820.tar.gz cpython-e318a883fece5d9a45165670b5f995886f524820.tar.bz2 |
Issue #15806: Add contextlib.ignored().
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/contextlib.py | 14 | ||||
-rw-r--r-- | Lib/test/test_contextlib.py | 22 |
2 files changed, 35 insertions, 1 deletions
diff --git a/Lib/contextlib.py b/Lib/contextlib.py index 0b6bf71..03c56da 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -4,7 +4,7 @@ import sys 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 @@ class closing(object): def __exit__(self, *exc_info): self.thing.close() +@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 index e52ed91..d13659d 100644 --- a/Lib/test/test_contextlib.py +++ b/Lib/test/test_contextlib.py @@ -594,6 +594,28 @@ class TestExitStack(unittest.TestCase): 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(): |