astral-sh / ruff

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

`PLR6301` not aware of `attrs` validation decorator #12568

Closed my1e5 closed 2 weeks ago

my1e5 commented 1 month ago

Related to https://github.com/astral-sh/ruff/issues/12172.

The attrs library, which is similar to dataclasses, uses decorators to allow you to define validators for the attributes of your class. Here is a simple example:

from attrs import define, field

@define
class Foo:
    x: int = field()

    @x.validator
    def validate_x(self, attribute, value):
        if value <= 0:
            raise ValueError("x must be a positive integer")

foo = Foo(x=-1) # ValueError: x must be a positive integer

However, this triggers PLR6301 - https://play.ruff.rs/2aa3e667-d733-4dc9-b1c7-307256edcabe

Method validate_x could be a function, class method, or static method

But in this situation, this is not correct. validate_x needs self in order to be valid.

Perhaps this is beyond the scope of PLR6301, but it would nice if Ruff was context-aware of attrs here.

my1e5 commented 1 month ago

I've tested this example code with the original pylint rule and it also raises an issue - R6301: Method could be a function (no-self-use).