ardupilot icon indicating copy to clipboard operation
ardupilot copied to clipboard

pre-commit: Add flake8-blind-except and flake8-bugbear

Open cclauss opened this issue 7 months ago • 2 comments

DRAFT: Do not merge.

Find 200+ instances of error-prone Python statements using flake8-blind-except and flake8-bugbear.

36    B006 Do not use mutable data structures for argument defaults.  They are created during function
            definition time. All calls to the function reuse this one instance of that data structure,
            persisting changes between them.
8     B008 Do not perform function calls in argument defaults.  The call is performed only once at function
            definition time. All calls to your function will reuse the result of that definition-time
            function call.  If this is intended, assign the function call to a module-level variable and
            use that variable as a default value.
10    B901 blind except: statement
148   B902 blind except Exception: statement
  • https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments
  • https://peps.python.org/pep-0008/#programming-recommendations

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

A good rule of thumb is to limit use of bare ‘except’ clauses to two cases:

  1. If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.
  2. If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise. try...finally can be a better way to handle this case.

cclauss avatar Jul 07 '25 07:07 cclauss

Some nice catches in there. I've been caught by B008 before.

peterbarker avatar Jul 07 '25 10:07 peterbarker

We've merged fixes for the B006 and B008 problems. We don't have any protection for them coming back in again.

How does one confidently move from bare-except and catching-Exception to catching all of the sensible things it is to catch? i.e. narrow those exceptions without missing any that you really should catch? Just on a case-by-case basis by hand?

peterbarker avatar Oct 27 '25 00:10 peterbarker