2

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?

sinoroc
  • 18,409
  • 2
  • 39
  • 70
matejcik
  • 1,912
  • 16
  • 26
  • What is the question? – sinoroc Mar 10 '23 at 11:33
  • the question is, what linter or static analysis tool can detect this problem? i thought that the title and the last line makes it obvious, but apparently not, so thanks for the notice, I edited the question – matejcik Mar 10 '23 at 16:54
  • Related: https://stackoverflow.com/questions/44282268/python-type-hinting-with-exceptions – sinoroc Mar 11 '23 at 09:48

1 Answers1

3

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

Pierre.Sassoulas
  • 3,733
  • 3
  • 33
  • 48