Skip to content

B042 has naive definition of exception #538

Open

Description

@GPHemsley-RELX

B042 (introduced in #421 / #512) has a naive way of determining whether a class is an exception:

flake8-bugbear/bugbear.py

Lines 1798 to 1802 in 915edea

def is_exception(s: str):
for ending in "Exception", "Error", "Warning", "ExceptionGroup":
if s.endswith(ending):
return True
return False

It is based solely on the name of the class, which means it returns True even if the class is not an exception.

For example, if I have a context manager class called FailOnException, it will trigger, even though that class is not an exception at all:

from typing import (ContextManager, TypeVar)
T = TypeVar("T")
class FailOnException(ContextManager[T]): pass

print(FailOnException.__mro__)
(<class '__main__.FailOnException'>, <class 'contextlib.AbstractContextManager'>, <class 'abc.ABC'>, <class 'typing.Generic'>, <class 'object'>)

Activity

  1. cooperlees commented on Feb 13, 2026

    @cooperlees
    Collaborator

    I get the "buggy" nature, but calling something an exception that isn't an exception is misleading right? Probably don't want to do that in Python ...

    But open to maybe using inheritance from BaseException etc. to be smarter here if others agree.

  2. GPHemsley-RELX commented on Feb 13, 2026

    @GPHemsley-RELX
    Author

    FailOnException is a context manager that catches exceptions and then fails gracefully; it's not calling itself an exception.

    I think checking for inheritance from BaseException is the only right way to do this, and indeed is a more Pythonic way.

    In Python, all exceptions must be instances of a class that derives from BaseException.

  3. DG-Elom commented on Oct 14, 2026

    @DG-Elom
    Contributor

    Checked on main: since #578, class FailOnException(ContextManager[T]) with an __init__ that doesn't call super().__init__() is no longer flagged by B042 (it was on the commit before). #578 only excludes parameterized generic bases rather than resolving real inheritance from BaseException, so I'll leave it to you whether that's enough to close this.

  4. GPHemsley-RELX commented on Oct 14, 2026

    @GPHemsley-RELX
    Author

    It sounds like it addresses my usecase (I haven't tested it yet), so thanks for that, but it sounds like it is still technically "naive", so I'll leave it open. 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions