Partial specialization of a generic type
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
I have have a generic class hierarchy, mirroring the hierarchy of the type parameter. I am trying to add proper type annotations to these classes.
In the example below (gist here) I'm attempting to partially specialize the Root class:
from typing import Generic, TypeVar
_T = TypeVar("_T")
class Root(Generic[_T]):
def __init__(self, value: _T):
self.value = value
_Number = TypeVar("_Number", int, float)
class FooNumber(Root[_Number]):
def __init__(self, value: _Number):
super().__init__(value)
... mypy reports on the __init__ upcall from FooNumber.__init__():
test-mypy-typevar-inherit.py:13: error: Argument 1 to "__init__" of "Root" has incompatible type "int"; expected "_Number" [arg-type]
test-mypy-typevar-inherit.py:13: error: Argument 1 to "__init__" of "Root" has incompatible type "float"; expected "_Number" [arg-type]
The goal is to then declare FooInt deriving from FooNumer[int] (and similarly for FooFloat).
A direct specialization of FooInt from Root[int] shows (as expected) no issue, and I don't feel it's very clear why this FooNumber definition causes any problem.
It seems there would be no reason for those errors.
Note: this point was first raised on Gitter and on stackoverflow
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 shown generic inheritance example, then inspect how mypy checks the FooNumber.init() upcall. Done means the partial specialization no longer produces the reported incompatible-type errors while FooInt and FooFloat can specialize FooNumber as intended.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100