astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
32k stars 1.07k forks source link

Mutable default argument not detected when it is a constant (by B006 and others) #11030

Open omgMath opened 6 months ago

omgMath commented 6 months ago

Hi I found a case where my expectations does not meet the results reported by ruff. But first, let's start with the issue basics:

Where my case.py contains the following lines:

DEFAULT_ENTRIES = [1, 2, 3]

def append_one(entries: list[int] = DEFAULT_ENTRIES) -> None:
    entries.append(1)

I would have hoped that this would be detected by rule B006 (or any other rule), but sadly it is not.

However, the rule detects the issue if instead of DEFAULT_ENTRIES we use []. Thanks for checking!

dhruvmanila commented 6 months ago

Thanks for the report. I believe this is the current limitation of many rules where they don't try to resolve the type of a variable. It will only check if it's a literal expression like [], {}, etc.

charliermarsh commented 6 months ago

I feel like we could catch this via the type annotation though?

dhruvmanila commented 6 months ago

Yeah, it should be doable

gerrymanoim commented 3 weeks ago

Just confirming that as of ruff 0.6.6 it still doesn't catch the constant via type annotations:

TEST = [1, 2, 3]

def test(l: list[int] = [1, 2, 3]):
    pass

def test2(l: list[int] = TEST):
    pass

Does https://github.com/astral-sh/ruff/pull/11122 need more work? Anything that we could help with?