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

R. David Murray rdmurray at bitdance.com
Sun Oct 13 20:09:16 CEST 2013


On Sun, 13 Oct 2013 13:58:56 -0400, Alexander Belopolsky <alexander.belopolsky at gmail.com> wrote:
> The feature (*and* its name) is a fine solution for the problem that
> it solves and is an improvement over status quo.
> 
> I find
> 
> with ignore(OSError):
>      os.unlink(path)
> 
> much easier to read than
> 
> try:
>    os.unlink(path)
> except OSError:
>    pass
> 
> Yes, this feature can be abused with multiple statements in the with
> block, but so can try/except.   People who write code using contextlib
> are expected to know that it is not a good idea to keep resources
> longer than necessary and multiple unrelated statements within the
> with block will raise a mental red flag.   It is also easy for
> lint-like tools to warn about abuse of ignore().

With blocks *very often* include multiple lines of code, because
the resource shouldn't be released until all those lines are done.
try/except blocks with more than a couple lines of code are a
code smell.  with replaces try/finally, not try/except.

I have no problem with Nick deciding that none of the arguments
convince him and leaving it in.  We'll see how it turns out 
in practice :)

--David


More information about the Python-Dev mailing list