Using Self with __init_subclass__ uses the base class as Self rather than the class being defined
Nobody has claimed this yet.
- 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
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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