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

Zero Piraeus z at etiol.net
Tue Oct 15 03:04:45 CEST 2013


:

On Tue, Oct 15, 2013 at 10:18:56AM +1000, Nick Coghlan wrote:
> I didn't articulate the point very well. The reason I originally
> approved the change (and the reason I have kept it despite the
> objections raised) is because it allows correct-but-ugly code like:
> 
>     try:
>         os.unlink(fname)
>     except FileNotFoundError:
>         pass
> 
> To be rewritten as the significantly more elegant:
> 
>     with ignore(FileNotFoundError):
>         os.unlink(fname)

I thought that was already clear, to be honest. As an aside, calling the
try/except construct above "ugly" seems a stretch to me - it's a little
verbose if you're going to be using it a lot, but presumably in that
case you'd just wrap it in a safe_unlink() convenience function if it
became annoying.

> This benefit when used correctly then needs to be weighed against the
> risk of it being used *incorrectly*, especially by people that expect
> it to work like VB's "on error resume next" rather than by suppressing
> the exception and resuming execution after the with statement.
> 
> The problem of overbroad exception handling isn't a new one, though,
> and I don't believe this feature makes that problem *worse*, and, by
> making it simpler and cleaner to suppress exceptions from a single
> statement, may make it better. For example, this code is wrong:
> 
>     try:
>         os.unlink(fname)
>         os.unlink(fname2)
>     except FileNotFoundError:
>         pass

Yes, it's bad code, but it's more intuitively obvious what it does (and
therefore that it's badly written) than the equivalent

    with ignore(FileNotFoundError):
        os.unlink(fname)
        os.unlink(fname2)

... as others have pointed out. The above suffers from the same
(famously solved by Python) problem as C code with inconsistent braces
and indentation: there's a disconnect between what it looks like and
what it does.

I think one problem is that ignore() doesn't actually do what its name
suggests - the flow of execution is changed if an exception occurs,
which by definition means the exception isn't being ignored.

Maybe it would be better to call it silence()? That's still not perfect
IMO, but it's closer to an accurate description of what's going on.

 -[]z.

-- 
Zero Piraeus: obiter dictum
http://etiol.net/pubkey.asc


More information about the Python-Dev mailing list