Search code examples
pythonstatic-analysispylint

Is there a Python linter to check for a missing `raise` keyword?


I have seen the following pattern several times:

if value > MAX_VALUE:
    ApplicationError("value is too large")

# value is in range now
use_value(value)

There is an obvious but relatively easy-to-miss bug here: the raise keyword is missing from ApplicationError. An exception object is constructed but not raised, and an invalid value continues to the rest of the function.

We use flake8, pyright, and a select set of pylint lints. My expectation is that some sort of static analysis tool would find this problem:

  • either by detecting that I'm creating an exception instance and not raising it,
  • or (easier) that I'm creating an instance of a class, but not storing the result (this could be used for side-effects but it's definitely an antipattern, right?)
  • or (most general) that there is a function call with unused result

The last option seems like something mypy/pyright should be capable of catching, at least, but I'm completely unable to find any sort of linter for this.

Is there a linting tool for Python code that can detect this problem (missing raise keyword) and how to configure it to do so?


Solution

  • pointless-exception-statement in pylint does what you want, this is a builtin check that is activated by default, see https://pylint.readthedocs.io/en/latest/user_guide/messages/warning/pointless-exception-statement.html