[Python-Dev] cpython: Rename contextlib.ignored() to contextlib.ignore().

Antoine Pitrou solipsis at pitrou.net
Fri Oct 11 11:00:42 CEST 2013


Let me answer here to Nick's argument on the tracker (made last year,
before the patch was committed):

> As with many context managers, a key benefit here is in the priming
> effect for readers. In this code:
> 
>     try:
>        # Whatever
>     except (A, B, C):
>        pass
> 
> the reader doesn't know that (A, B, C) exceptions will be ignored
> until the end. The with statement form makes it clear before you
> start reading the code that certain exceptions won't propagate:
> 
>     with ignored(A, B, C):
>         # Whatever

The problem with this argument is that it assumes a very specific idiom:
i.e. writing long "try" blocks in the purpose of silencing exceptions.

I'd like to make the following points:

- when catching an exception, the common (and recommended) behaviour is
  to do something else - not merely silencing it.  Silencing is not very
  common in my experience, except in badly written code

- when catching an exception, it is recommended for the "try" block to
  be as slim as possible - so that you don't catch other unintended
  exceptions by mistake. This is a point I already made in PEP 3151.
  Many exception classes (OSError, KeyError, RuntimeError...) are
  polysemic.

The bottom line is that there shouldn't be any long "try" blocks
followed by a single "except FooException: pass" clause in well-written
code. The presence of such an idiom is a strong code smell.

Therefore contextlib.ignore() seems aimed at making it easier to write
bad code, not good code. I don't think it should exist in the stdlib.

Regards

Antoine.




More information about the Python-Dev mailing list