Skip to content

B006 preview fix adds an annotation to a previously annotated variable #20864

@dscorbett

Description

@dscorbett

Summary

In preview, the fix for mutable-argument-default (B006) copies the parameter’s annotation into the body of the function, causing errors in some type-checkers. Even in type-checkers which allow reannotation, it is unnecessary. Example:

$ cat <<'# EOF' | tee >b006.py b006_preview.py
def f(x: list[int] = []) -> int:
    return sum(x)
# EOF

$ ruff --isolated check b006_preview.py --select B006,RUF013 --unsafe-fixes --fix --preview
Found 2 errors (2 fixed, 0 remaining).

$ cat b006_preview.py
def f(x: list[int] | None = None) -> int:
    if x is None:
        x: list[int] = []
    return sum(x)

$ mypy b006_preview.py
b006_preview.py:3: error: Name "x" already defined on line 1  [no-redef]
b006_preview.py:4: error: Argument 1 to "sum" has incompatible type "list[int] | None"; expected "Iterable[bool]"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

$ pyright b006_preview.py | sed 's:/.*\(b006_preview\.py\):\1:'
b006_preview.py
  b006_preview.py:1:7 - error: Parameter declaration "x" is obscured by a declaration of the same name (reportRedeclaration)
1 error, 0 warnings, 0 informations

Compare the non-preview behavior:

$ ruff --isolated check b006.py --select B006,RUF013 --unsafe-fixes --fix
Found 2 errors (2 fixed, 0 remaining).

$ cat b006.py
def f(x: list[int] | None = None) -> int:
    if x is None:
        x = []
    return sum(x)

$ mypy b006.py
Success: no issues found in 1 source file

$ pyright b006.py
0 errors, 0 warnings, 0 informations

Version

ruff 0.14.0 (beea8cd 2025-10-07)

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingfixesRelated to suggested fixes for violationspreviewRelated to preview mode features

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions