ruff: N805 False Positive

Noticed that ruff gives a false positive with pydantic validation method as shown here:

class MyClass(BaseModel):
    name: str

    @validator('name')
    def name_validator(cls, v):
        if v is None:
            return "John Smith"
        else:
            return v

Running ruff . --fix gives me the following message: ...N805 First argument of a method should be named "self" Ruff Version: ruff 0.0.246

Sections from pyproject.toml:

[tool.ruff]
fix = true
line-length = 120
target-version = "py39"
select = ["I", "E", "F", "Q", "W", "N"]
ignore = [
    "F541",
    "N803",
    "N806",
    "Q000",
    "Q003",
]
[tool.ruff.pydocstyle]
convention = "numpy"

[tool.ruff.flake8-quotes]
avoid-escape = false
inline-quotes = "double"
docstring-quotes = "double"
multiline-quotes = "double"

[tool.ruff.isort]
known-first-party = [
    "tools"
]

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 1
  • Comments: 17 (8 by maintainers)

Most upvoted comments

Yeah you should be able to add:

[tool.ruff.pep8-naming]
# Allow Pydantic's `@validator` decorator to trigger class method treatment.
classmethod-decorators = ["classmethod", "pydantic.validator"]

…to help with this. But if that doesn’t work, let us know!

Also a fair point, I’ll just leave the issue raising decision to the team. Either Pydantic’s @classmethod recommendation or https://github.com/astral-sh/ruff/issues/2868#issuecomment-1836564993 are explicit, existing solutions with some repetition burden. Implicit defaults would eliminate repetition at the expense of more special-casing, a slippery slope. I would say that we’re getting into bikeshedding, but I guess if there’s anywhere that it’s appropriate to bikeshed, it would be in the closed issue section of a linter/formatter.

I was bit by this old issue again when bumping a project to Pydantic v2 while still using the old interface (e.g. from pydantic.v1 import ...). It’s simple enough to fix, but it took me a minute to figure out, so I figured I’d detail it here in case a search engine brings you here as well. You must add pydantic.v1.validator to your classmethod-decorators.

[tool.ruff.pep8-naming]
classmethod-decorators = ["pydantic.validator", "pydantic.v1.validator"]

Amazing, thank you for the kind words! (I think this was broken for a release or two due to an internal refactor, but should be fixed in the last few.)

I realized the issue. I was on an earlier version of ruff (my poetry.lock file cause me to go back a version). Sorry to bother you guys! Great job on the application! i heard about you on the python podcast and since then have been a convert 😄 Getting everyone to use it 👍

That does not work either sadly. Just tried it.

Thank you! Will do 😃