python / python/mypy

Using Self with __init_subclass__ uses the base class as Self rather than the class being defined

Open
#15,807 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-self-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

I wanted to define two type hierarchies: model types, and handlers that are contravariant over models, where models can specify their handlers as class keyword arguments. I've included a simplified example in the To Reproduce section below.

The problem seems to be that, when __init_subclass__ runs for Foo, it's treating Self as if it were Model rather than Foo, which fails because T is contravariant and FooHandler is not a subtype of Handler[Model].

To Reproduce

Playground Link

from __future__ import annotations
from typing import Any, ClassVar, Self, TypeVar, Generic


T = TypeVar("T", bound="Model", contravariant=True)

class Handler(Generic[T]):
    pass

class Model:
    handler: ClassVar[type[Handler[Self]]]
    
    def __init_subclass__(cls, *, handler: type[Handler[Self]]) -> None:
        super().__init_subclass__()
        cls.handler = handler


class FooHandler(Handler[Foo]):
    pass

class Foo(Model, handler=FooHandler):
    pass

Expected Behavior

I expected mypy to treat Self as Foo when running Model.__init_subclass__(Foo, ...).

Actual Behavior

main.py:15: error: Incompatible types in assignment (expression has type "type[Handler[Self]]", variable has type "type[Handler[Model]]")  [assignment]
main.py:21: error: Argument "handler" to "__init_subclass__" of "Model" has incompatible type "type[FooHandler]"; expected "type[Handler[Model]]"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.4.1 and master branch (both from playground)
  • Python version used: 3.11

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked mypy-play reproducer and the handling of Self in Model.init_subclass. Verify how Self is resolved when Foo is defined, then run the example against mypy to confirm that the assignment and handler argument errors are resolved without weakening the reported type relationships.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.