[Python-Dev] "with" use case: replacing a file
Phillip J. Eby
pje at telecommunity.com
Thu May 12 22:34:06 CEST 2005
At 03:00 PM 5/12/2005 -0500, Ka-Ping Yee wrote:
>This is all so intricate i'm not sure if i got it right. Somebody
>let me know if this looks right or not. (In any case, i look forward
>to the day when i can rely on someone else to get it right, and they
>only have to write it once!)
It looks fine, but it's not a use case for suppressing exceptions, nor was
the exception-chaining example.
Really, the only use case for suppressing exceptions is to, well, suppress
exceptions that are being logged, shown to the user, sent via email, or
just plain ignored. Guido's point, I think, is that these use cases are
rare enough (yet simple and similar enough) that they don't deserve support
from the cleanup facility, and instead should use a try/except block.
After reviewing the cases in my own code where I might've used a 'with
logged_exceptions()' or similar blocks, I think I now agree. The
difference between:
try:
BLOCK
except:
logger.exception(...)
and:
with log_errors(logger):
BLOCK
doesn't seem worth the effort, especially since this pattern just doesn't
occur that often, compared to resource-using blocks.
What *your* use cases seem to illustrate, however, is that it's quite
possible that an __exit__ might well need to contain complex error handling
of its own, including the need to throw a different exception than the one
that was passed in.
More information about the Python-Dev
mailing list