redline
HighError handlingmutable-default

Mutable default argument

Mutable default argument. A mutable default in f. It's created once and shared by every call, so one call's changes leak into the next.

This is how the comment reads inline, under the flagged line.

Why it matters

Python evaluates defaults once. A list or dict default is shared by every call, so state leaks between calls.

What to do

Default to None and create the value inside the function.

Examples

Flagged
def add(item, items=[]):
    items.append(item)
Better
def add(item, items=None):
    items = [] if items is None else items

What it catches

It reads the shape of the code: functions, blocks, loops and calls. Languages: Python. Scope: All files. These cases are the rule's own tests: the first set must be flagged and the second must not.

Flagged

def f(x=[]):
    return x
def f(*, x={}):
    return x

Left alone

def f(x=None):
    return x

Research

Mutable default arguments in Python. The default is built once and shared by every call.

Turn it off or change it

In a config file for the CLI, or in the API's rules field:

{
  "rules": {
    "disable": [
      "mutable-default"
    ],
    "severity": {
      "mutable-default": "low"
    }
  }
}

Read the source or report a false positive.