PyCQA / PyCQA/flake8-bugbear

Suggestion: Ignore B006 if the variable in question is immediately copied

Open
#137 14 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.1k
Forks
123
Avg merge
2d 5h
Merged PRs (30d)
5

Description

I would argue that these two functions:

def foo(x=[]):
    x = list(x)
    x.reverse()
    return x

def bar(x={}):
    x = dict(x)
    x.pop('k', None)
    return x

are far more readable than the way B006 forces me to write them

def foo_bad(x=None):
    if x is None:
        x = []
    x.reverse()
    return x

def bar_bad(x=None):
    if x is None:
        x = {}
    x.pop('k', None)
    return x

Furthermore, the rewrite encouraged by B006 now actually leads to a bug - x = [1]; foo_bad(x) leads to x being mutated.

Would it be possible/sensible to add an exemption to B006 along the lines of "if the only use of the mutable default is to pass into a non-mutating function call, then emit no warning"?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Review B006's current handling of mutable defaults and the examples in the issue. Determine whether an immediately copied default can be distinguished safely from later mutation, then define tests covering foo, bar, and the existing B006 behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.