How to get a warning about a list being a mutable default argument?

Question:

I accidentally used a mutable default argument without knowing it.

Is there a linter or tool that can spot this and warn me?

Asked By: Pascal T.

||

Answers:

flake8-bugbear, Pylint, PyCharm, and Pyright can detect this:

  • Bugbear has B006 (Do not use mutable data structures for argument defaults).

    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.

  • Pylint has W0102 (dangerous default value).

    Used when a mutable value as list or dictionary is detected in a default value for an argument.

  • Pyright has reportCallInDefaultInitializer.

    Generate or suppress diagnostics for function calls, list expressions, set expressions, or dictionary expressions within a default value initialization expression. Such calls can mask expensive operations that are performed at module initialization time.

    This does what you want, but be aware that it also checks for function calls in default arguments.

  • PyCharm has Default argument’s value is mutable.

    This inspection detects when a mutable value as list or dictionary is detected in a default value for an argument.

    Default argument values are evaluated only once at function definition time, which means that modifying the default value of the argument will affect all subsequent calls of the function.

    Unfortunately, I can’t find online documentation for this. If you have PyCharm, you can access all inspections and navigate to this inspection to find the documentation.

Answered By: pigrammer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.