Error linting Pydantic Base Model Extension as return type of a method

  • Operating system: macOS Sonoma Version 14.2.1
  • SonarLint plugin version: 10.5.0.78339
  • Programming language you’re coding in: Python
  • Is connected mode used: No
    • Connected to SonarCloud or SonarQube (and which version):

And a thorough description of the problem / question:

This is a very short example of what is going wrong

from pydantic import BaseModel
from typing import cast
from typing_extensions import reveal_type
class SomeModel(BaseModel):
    name: str = "test"
    pass

class Service():
    @classmethod
    def foo(cls) -> SomeModel:
        obj = SomeModel().parse_obj({})
        print(type(obj), reveal_type(obj))  # > Runtime type is 'SomeModel' <class '__main__.SomeModel'> name='test'

        #obj = cast(SomeModel, obj). # this will resolve the warning of course
        return obj

the warning I get:

Return a value of type “SomeModel” instead of “BaseModel” or update function “foo” type hint.

This is the signature of BaseModel.parse_obj

@classmethod
    def parse_obj(cls: Type['Model'], obj: Any) -> 'Model':

Then I don’t see why a warning should appear

Hello,

Thanks for reporting this false-positive. I have reproduced it and created SONARPY-1870.

Have a great day.

1 Like