[issue27814] contextlib.suppress: Add whitelist argument

Nick Coghlan report at bugs.python.org
Tue Aug 23 08:02:28 EDT 2016


Nick Coghlan added the comment:

Thanks for being understanding of the decision. Regarding my comment above about __subclasscheck__ potentially letting you implement this without changing the signature of suppress, here's an example of how you might be able to do that.

First, define a metaclass that delegates type checks to the type itself (similar to abc.ABCMeta):

class FilteredExceptionMeta(type):
    def __subclasscheck__(cls, other):
        return cls.__subclasshook__(other)
    def __instancecheck__(cls, other):
        return cls.__subclasshook__(type(other))

Then, define a factory function to create custom classes based on that metaclass:

def filtered_exc(exc_type, *, unless=()):
    class _FilteredException(metaclass=FilteredExceptionMeta):
        @classmethod
        def __subclasshook__(cls, other):
            return (issubclass(other, exc_type)
                    and not issubclass(other, unless))
    return _FilteredException


>>> from contextlib import suppress
>>> selective_filter = suppress(filtered_exc(OSError, unless=FileNotFoundError))
>>> with selective_filter:
...     raise OSError("Suppressed")
... 
>>> with selective_filter:
...     raise FileNotFoundError("Not suppressed")
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FileNotFoundError: Not suppressed

This works because suppress() calls issubclass() explicitly, unlike the current implementation of except clause processing.

----------

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


More information about the Python-bugs-list mailing list