Permalink
Browse files

Add context manager for the "try: ... except: pass" pattern.

  • Loading branch information...
1 parent df15b45 commit bf439ba62ee9fb3456eef5f3eb7f6f7894e66733 @berkerpeksag committed Sep 1, 2012
Showing with 61 additions and 0 deletions.
  1. +61 −0 contextmanager-ignore.py
View
@@ -0,0 +1,61 @@
+# coding: utf-8
+
+from contextlib import contextmanager
+
+"""
+Add context manager for the "try: ... except: pass" pattern
+
+It is a somewhat common pattern to write:
+
+ try:
+ do_something()
+ except SomeException:
+ pass
+
+http://bugs.python.org/issue15806
+"""
+
+
+@contextmanager
+def ignored(*exceptions):
+ """Context manager to ignore particular exceptions.
+
+ While the class based version would likely be fractionally faster, the
+ generator based version is more obviously correct."""
+ try:
+ yield
+ except exceptions:
+ pass
+
+
+class Ignore:
+ """Context manager to ignore particular exceptions."""
+
+ def __init__(self, *ignored_exceptions):
+ self.ignored_exceptions = ignored_exceptions
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exctype, excinst, exctb):
+ return exctype and issubclass(exctype, self.ignored_exceptions)
+
+
+def main():
+ d = dict()
+
+ # decorator version
+ with ignored(KeyError):
+ del d['spam']
+
+ # class-based version
+ with Ignore(KeyError):
+ del d['spam']
+
+ try:
+ del d['spam']
+ except KeyError:
+ pass
+
+if __name__ == '__main__':
+ main()

0 comments on commit bf439ba

Please sign in to comment.