KEMBAR78
`Self` type of `ClassVar` lost through `TypeVar` · Issue #17395 · python/mypy · GitHub
Skip to content

Self type of ClassVar lost through TypeVar #17395

@asottile-sentry

Description

@asottile-sentry

this is very similar to #16826 but appears to be slightly different

Bug Report

Self appears to be decaying to the TypeVar bound instead of the TypeVar itself. my specific example looks similar to django models construction but is isolated from django-stubs itself to make a minimal reproduction

it works great for the subclass (as demonstrated by the first reveal_type) -- just not for the TypeVar

To Reproduce

from typing import TypeVar, Generic, ClassVar, Self

M = TypeVar("M", bound="B", covariant=True)

class Related(Generic[M]):
    def get(self) -> M:
        raise NotImplementedError

class B:
    objects: ClassVar[Related[Self]] = Related()

class C(B):
    pass

reveal_type(C.objects)

def of_m(cls: type[M]) -> M:
    return cls.objects.get()

Expected Behavior

(no errors)

Actual Behavior

t.py:15: note: Revealed type is "t.Related[t.C]"
t.py:18: error: Incompatible return value type (got "B", expected "M")  [return-value]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.10.0
  • Mypy command-line flags: (none)
  • Mypy configuration options from mypy.ini (and other config files): (n/a)
  • Python version used: 3.12.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions