29 Aug 2012 07:15
[issue15806] Add context manager for the "try: ... except: pass" pattern
Raymond Hettinger <report <at> bugs.python.org>
2012-08-29 05:15:15 GMT
2012-08-29 05:15:15 GMT
New submission from Raymond Hettinger:
It is a somewhat common pattern to write:
try:
do_something()
except SomeException:
pass
To search examples in the standard library (or any other code base) use:
$ egrep -C2 "except( [A-Za-z]+)?:" *py | grep -C2 "pass"
In the Python2.7 Lib directory alone, we find 213 examples.
I suggest a context manager be added that can ignore specifie exceptions. Here's a possible implementation:
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 in self.ignored_exceptions
(Continue reading)
RSS Feed