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.
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!
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
Add this string above decorators:
# noinspection PyNestedDecorators
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With