astral-sh / ruff

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

[Feature Request] Add a rule that warns about assigning None #13477

Open serjflint opened 1 month ago

serjflint commented 1 month ago

Hi! I am switching linters in my codebase from flake8+pylint to ruff.

I found an interesting bug in the code. People use var = None as a placeholder for values before a loop or a condition. The problem is that mypy considers that as var: None = None.

Can ruff warn about that misuse and propose a change var: SomeType | None = None?

MichaReiser commented 1 month ago

Welcome to the ruff users :)

Because you're mentioning pylint and flake8: Do you know if pylint or flake8 have a rule that captures this pattern?

To clarify my understanding. You're referring to code like this (but it applies to all kinds of loops):

var = None

for x in range(1, 10):
    var = x

print(x)

But it doesn't apply if the for loop has an orelse branch where the variable is assigned unconditionally (both in the for body and the orelse).

I'm a bit hesitant of adding such a rule because it assumes specific mypy behavior. We're in the process of building a type checker and our type checker would correctly infer the var type as int | None if it is unannotated. I also suspect that implementing said rules requires implementing something close to a type checker to have a low false positive rate.