PyCQA / flake8-bugbear

A plugin for Flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycodestyle.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

B902: False positive when using the attrs library

henzef opened this issue · comments

The adaptions to B902 cause a regression when using the attrs library:

import attrs
from typing import Any


@attrs.frozen
class SpamAndEggs:
    foobar: list[int] = attrs.field()

    @foobar.validator
    def _positive(
        self,
        attribute: "attrs.Attribute[list[int]]",
        value: Any,
    ) -> None:
        if any(i < 0 for i in value):
            raise ValueError()


SpamAndEggs([1, 2, 3])

The error is:

myfile.py:11:9: B902 Invalid first argument 'self' used for class method. Use the canonical first argument name in methods, i.e. cls.

My suggestion would be to remove validator and root_validator from the default list and allow pydantic user to set them via the commandline flag. I would imagine that other libraries also have @validator decorators or that some people write their own

Maybe @jakkdl or @Zac-HD have an idea how to fix it? I think attrs is a pretty common library, so it would be great if someone could fix it.

With --classmethod-decorators you can overwrite the default values, so if you use --classmethod-decoraters=classmethod you'll suppress the errors.

The question is mostly what the default should be, but could maybe also update the documentation.

I ran into this as well. I think a sensible default is just classmethod. If the checker can also include the python package of the decorator, then it makes sense to include some additional defaults. For instance, @validator in attrs is not a classmethod, but it is in Pydantic.

Being conservative with the defaults is probably the way to go, feel free to open a PR changing it + the docs. It should be quite painless to implement.