flake8-bugbear icon indicating copy to clipboard operation
flake8-bugbear copied to clipboard

Suggestion: Forbid function/method calls in except statement

Open jaap3 opened this issue 4 years ago • 3 comments

Recently I "fixed" issue #171 (by which I mean, let bugbear not crash when encountering function calls in a except statement). But maybe that pattern shouldn't be allowed at all?

E.g. it's not possible for bugbear to enforce B013 or B014 if the return value of the call is not determined, which means that the following code is currently "fine" according to bugbear:

def foo():
    return (Exception,)


try:
    ...
except foo():
    ...
def bar():
    return (LookupError, KeyError, IndexError)


try:
    ...
except bar():
    ...

jaap3 avatar Oct 11 '21 09:10 jaap3

Hi there, I'm going to be honest, this seems a pretty rare use case here ... but if it breaks nothing else and we give a good reason as to why it should not be done (trying to workout the use case) I would accept as I don't want this code in my code bases.

cooperlees avatar Oct 13 '21 00:10 cooperlees

The only use-case I've seen "in the wild" is in a Django project. All model classes have specific DoesNotExist and MultipleObjectsReturned error classes. And the User model is configurable, which can cause people to write code like this:

django.contrib.auth import get_user_model


def get_user_by_email(email):
    try:
        return get_user_model().get(email=email)
    except (
        get_user_model().DoesNotExist,
        get_user_model().MultipleObjectsReturned
    ):
        pass

jaap3 avatar Oct 13 '21 07:10 jaap3

In Hypothesis, we have: (edited for brevity)

        except (FailedHealthCheck,) + skip_exceptions_to_reraise():
            raise
        except failure_exceptions_to_catch() as e:  # check it out, breaks the syntax highlighting!

and these have to be dynamic because what to catch depends on which modules have been imported.

Zac-HD avatar Oct 25 '21 01:10 Zac-HD

There are also cases like anyio.get_cancelled_exc_class(), so I don't think banning such calls is feasible.

Zac-HD avatar Nov 30 '22 05:11 Zac-HD