sbdchd / django-types

:doughnut: Type stubs for Django
MIT License
186 stars 62 forks source link

Classmethod returning `Self` makes Pylance raise `reportReturnType` #226

Closed simensol closed 6 months ago

simensol commented 7 months ago

When my custom managers went from untyped:

objects  = GroupManager()

to typed:

objects: ClassVar[GroupManager] = GroupManager()

classmethods returning Self, e.g.:

@classmethod
def create(
    cls,
    name: str
) -> Self:
    return cls.objects.create(
        name=name,
    )

started to raise the following linting error:

Expression of type "Group" cannot be assigned to return type "Self@Group"
  Type "Group" cannot be assigned to type "Self@Group" Pylance(reportReturnType)

I fixed this by returning "Group" instead:

@classmethod
def create(
    cls,
    name: str
) -> "Group":
    return cls.objects.create(
        name=name,
    )

However, according to PEP 673, a classmethod should be able to return Self.

sbdchd commented 7 months ago

Hmm is this a pyright issue?

simensol commented 6 months ago

Correct types solved the issue. See https://github.com/microsoft/pyright/issues/7251#issuecomment-1940625332 for solution.