Skip to content

Self used in contravariant positions #2605

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jorenham opened this issue Apr 11, 2025 · 1 comment
Open

Self used in contravariant positions #2605

jorenham opened this issue Apr 11, 2025 · 1 comment
Labels
bug Something isn't working

Comments

@jorenham
Copy link
Contributor

In e.g. django.db.models.Model.[a]refresh_from_db, Self is used in a contravariant position:

def refresh_from_db(
self,
using: str | None = None,
fields: Iterable[str] | None = None,
from_queryset: QuerySet[Self] | None = None,
) -> None: ...
async def arefresh_from_db(
self,
using: str | None = None,
fields: Iterable[str] | None = None,
from_queryset: QuerySet[Self] | None = None,
) -> None: ...

When I override this in my own model as e.g.

    @override
    def refresh_from_db(
        self,
        using: str | None = None,
        fields: Iterable[str] | None = None,
        from_queryset: QuerySet[Self] | None = None,
    ) -> None:

it violates the LSP, as explained in https://discuss.python.org/t/unsoundness-of-contravariant-self-type/86338. On pyright>=1.1.399, it will reportIncompatibleMethodOverride.

The workaround is to instead use QuerySet[Any] in the code above.

Perhaps a self: T with QuerySet[T] could work here? I'm not sure whether that'd make it theoretically sound, but it might be worth a shot 🤷🏻.

System information

  • OS: irrelevant
  • python version: 3.13
  • django version: 5.2
  • mypy version: pyright==1.1.399 or basedpyright==1.28.5
  • django-stubs version: 5.1.3
  • django-stubs-ext version: 5.1.3
@jorenham jorenham added the bug Something isn't working label Apr 11, 2025
@sobolevn
Copy link
Member

PR is welcome! Thanks for noticing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Development

No branches or pull requests

2 participants