python / python/mypy

Partial specialization of a generic type

Open
#14,262 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
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

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 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.