Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pydantic validation PyCharm: This decorator will not receive a callable it may expect; the built-in decorator returns a special object

from pydantic import BaseModel


class Request(BaseModel):
    num: int

    @validator("num")
    @classmethod
    def validate_num(cls, num: int) -> int:
        return num

PyCharm gives the warning "This decorator will not receive a callable it may expect; the built-in decorator returns a special object" for the above code. I don't think the warning is clear so I'd appreciate some help.

When I change the above code to this:

from fastapi.exceptions import RequestValidationError

from pydantic import BaseModel, validator
from pydantic.error_wrappers import ErrorWrapper


class Request(BaseModel):
    num: int

    @classmethod
    @validator("num")
    def validate_num(cls, num: int) -> int:
        if num < 0:
            raise RequestValidationError([ErrorWrapper(ValueError("error"), ())])
        return num


request = Request(num=-2)

The warning goes away, but the code executes without any problem when it's not supposed to, meaning that the validation has been ignored for some reason.

like image 330
BovineScatologist Avatar asked Dec 07 '25 06:12

BovineScatologist


2 Answers

Looking at the source code on github, you'll see that the validator decorator already returns a classmethod.

def validator(
    *fields: str,
    mode: Literal['before', 'after', 'wrap', 'plain'] = 'after',
    check_fields: bool | None = None,
    sub_path: tuple[str | int, ...] | None = None,
    allow_reuse: bool = False,
) -> Callable[[Callable[..., Any]], classmethod[Any]]:

Simply remove your @classmethod decorator!

like image 79
Stateless Avatar answered Dec 09 '25 19:12

Stateless


Your code is correct

It's false positive hint in PyCharm

Related issue: https://youtrack.jetbrains.com/issue/PY-34368/False-warning-This-decorator-will-not-receive-a-callable-it-may-expect-when-classmethod-is-not-the-last-applied

Workaround

Add this string above decorators:

# noinspection PyNestedDecorators
like image 44
Oleg Avatar answered Dec 09 '25 20:12

Oleg