[Python-ideas] Bad code exceptions (was PEP-3151 pattern-matching)

Mike Graham mikegraham at gmail.com
Fri Apr 8 21:15:24 CEST 2011


On Fri, Apr 8, 2011 at 2:32 PM, Guido van Rossum <guido at python.org> wrote:
> On Fri, Apr 8, 2011 at 11:22 AM, Mike Graham <mikegraham at gmail.com> wrote:
>> def my_event_loop(self):
>>    while True:
>>        try:
>>            self.advance()
>>        except BaseException as e:
>>             self.logger.exception()
>>             if isinstance(e, (NameError, AttributeError,
>>                               KeyboardInterrupt, SystemExit,
>>                               MemoryError)):
>
> You seem to be missing the reason why we introduced BaseException
> here... Read PEP 352.

I think I get what BaseException was conceived for, but it usually
proves unsuitable for my usage. If I just do "except Exception" in
this code (is that the idea?), it doesn't behave like I'd want:
a) If my program exits due to a KeyboardInterrupt, it doesn't make it
into my log, which I may want.
b) If my program exits due to a loose GeneratorExit, it doesn't make
it into my log, which I almost certainly want, and
c) Plenty of Exception subclasses (like MemoryError and any sort of
candidate for BadCodeError) are things that should be treated as
uncatchable as often as the exceptions which don't subclass Exception.

Perhaps I'm letting this cloud my vision of why you want BadCodeError.

>> Catchall exceptions (even of a slightly more limited nature) should be
>> a rarity and typically is caused by bugs. Since this is something that
>> should seldom be done and since there are borderline cases, I don't
>> think that a language-level change helps.
>
> But honestly that wasn't my intended use case. I was thinking more
> along the lines of trying to catch OSError with a specific errno
> value:
>
> except OSError as e if e.errno == errno.ENOTOBACCO:
>  logging.info('Pipe has no tobacco')

I'm confused how that relates to BadeCodeError?

> I don't think we can define "negative" exception classes.

class NotBadCodeError(Exception):
    __metaclass__ = abc.ABCMeta

    @classmethod
    def __subclasshook__(self, potential_subclass):
        if not issubclass(potential_subclass, BadCodeError):
            return True
        return False

DON'T JUDGE ME!

> But it's too late for that -- BadCodeError must derive from Exception,
> and most 3rd party code also defines exceptions deriving from
> Exception.
Right.


Mike



More information about the Python-ideas mailing list