Fixing Mutable Defaults

Recently, I noticed a number of warnings being picked up by my IDE when looking over some old code. Things that don’t loudly make themselves know can slip under the radar in a large codebase.
Given it was a fairly typical issue (mutable default arguments, which this article by The Hitchhiker’s Guide to Python nicely explains), I was surprised that it wasn’t being picked up by flake8, which I had introduced to our CI process previously, and often points out common issues with your code.

After a little searching I found a flake8 plugin, flake8-bugbear, that covered mutable default arguments and other issues. Which included an explanation of why these checks were not in the base flake8:

It is felt that these lints don’t belong in the main Python tools as they are very opinionated and do not have a PEP or standard behind them. Due to flake8 being designed to be extensible, the original creators of these lints believed that a plugin was the best route. This has resulted in better development velocity for contributors and adaptive deployment for flake8 users.

So I updated the configuration of pre-commit (which is part of our CI pipeline) to include the following:

repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v2.3.0
    hooks:
    -   id: flake8
        additional_dependencies: ['flake8-bugbear']
    ...

So now everyone who is adding to the codebase will be warned about these common issues too!

Additionally, during my search I came across this Awesome list of flake8 plugins which has many more plugins for flake8 which I will be checking through to see if any seems particularly useful.