[issue27814] contextlib.suppress: Add whitelist argument

Nick Coghlan report at bugs.python.org
Sat Aug 20 13:00:22 EDT 2016


Nick Coghlan added the comment:

Michael, first of all, thanks for taking the time to propose this idea, and put together a patch for it.

Unfortunately, I'm going to have to decline the proposal for API design reasons (which I'll explain below), and instead point you towards https://bugs.python.org/issue12029 which aims to fix a limitation in the normal exception handling that prevents custom __subclasscheck__ hooks from being usable in normal except clauses.

This is a more significant proposed change to the language than it first appears, as Python has never really had a concise fully standardised "catch these exceptions, but not these ones" syntax, with your options being limited to a preceding "except <excluded types>: raise" clause, or doing an isinstance() check on an already caught exception.

I'm also not sure it's an idiom we really want to encourage, as it tends to age poorly as new exception subclasses are added, as well as confusing exception flow logic like the example given in the documentation, which would be clearer with a single inline exception statement and a well-named flag variable:

    run_optional_code = True
    try:
        os.remove(somefile)
    except PermissionError:
        run_optional_code = False
    except OSError:
        pass
    if run_optional_code:
        # Executed on success and on OSError
        # other than PermissionError
        # In a real example, "run_optional_code" would
        # be replaced by a name that actually conveyed
        # useful information to future readers

For folks that do need this capability, building it themselves is pretty straightforward, and if they go so far as to define a custom __instancecheck__ and __subclasscheck__ implementation, that will already work with contextlib.suppress(), but would need https://bugs.python.org/issue12029 to land to work with ordinary except clauses.

----------
resolution:  -> rejected
stage: patch review -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue27814>
_______________________________________


More information about the Python-bugs-list mailing list