TypeVar bound doesn't understand CRTP
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Ideally, this snippet would work. It enables making multiple types that share the same implementation but don't subclass each other (like newtype in other languages). If you comment out the other.quack() call and the bound="Foo[DerivedT]") then it will typecheck -- the issue is specifically with being able to express a typevar bound indicating the typevar has a base class that uses that typevar as a generic parameter.
#!/usr/bin/env python
from __future__ import annotations
from typing import Generic, TypeVar
DerivedT = TypeVar("DerivedT", bound="Foo[DerivedT]")
class Foo(Generic[DerivedT]):
def quack(self) -> None:
print("quack!")
def quack_together(self, other: DerivedT) -> None:
self.quack()
other.quack()
class Bar(Foo[Bar]): pass
x = Bar()
y = Bar()
x.quack_together(y)
$ python -m mypy --strict /tmp/self_test.py
self_test.py:6: error: Type variable "self_test.DerivedT" is unbound [valid-type]
self_test.py:6: note: (Hint: Use "Generic[DerivedT]" or "Protocol[DerivedT]" base class to bind "DerivedT" inside a class)
self_test.py:6: note: (Hint: Use "DerivedT" in function signature to bind "DerivedT" inside a function)
Found 1 error in 1 file (checked 1 source file)
- Mypy version used: mypy 1.10.0 (compiled: yes)
- Mypy configuration options from
mypy.ini(and other config files): N/A - Python version used: 3.12
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
The reproducer is /tmp/self_test.py; start by running python -m mypy --strict /tmp/self_test.py with the shown CRTP bound. Investigate how mypy reports the unbound TypeVar, and consider the work complete when the example type-checks without that error while preserving the type relationship described.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100