flake8-bugbear
flake8-bugbear copied to clipboard
Suggestion: Forbid function/method calls in except statement
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():
...
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.
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
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.
There are also cases like anyio.get_cancelled_exc_class(), so I don't think banning such calls is feasible.