Message169337
| Author |
rhettinger |
| Recipients |
ncoghlan, rhettinger |
| Date |
2012年08月29日.05:15:14 |
| SpamBayes Score |
-1.0 |
| Marked as misclassified |
Yes |
| Message-id |
<1346217315.31.0.832549559428.issue15806@psf.upfronthosting.co.za> |
| In-reply-to |
| Content |
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
The usage would be something like this:
with Ignore(IndexError, KeyError):
print(s[t])
Here's a real-world example taken from zipfile.py:
def _check_zipfile(fp):
try:
if _EndRecData(fp):
return True # file has correct magic number
except IOError:
pass
return False
With Ignore() context manager, the code cleans-up nicely:
def _check_zipfile(fp):
with Ignore(IOError):
return bool(EndRecData(fp)) # file has correct magic number
return False
I think this would make a nice addition to contextlib. |
|
History
|
|---|
| Date |
User |
Action |
Args |
| 2012年08月29日 05:15:15 | rhettinger | set | recipients:
+ rhettinger, ncoghlan |
| 2012年08月29日 05:15:15 | rhettinger | set | messageid: <1346217315.31.0.832549559428.issue15806@psf.upfronthosting.co.za> |
| 2012年08月29日 05:15:14 | rhettinger | link | issue15806 messages |
| 2012年08月29日 05:15:14 | rhettinger | create |
|