python / python/mypy

generic subclasss and typevar with constraint

Open
#7,362 10 comments 7 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-1-normal topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Not sure if this is a "bug" or I didn't understand generics, but

import typing

T = typing.TypeVar('T', str, int)


class Base(typing.Generic[T]):

    def __init__(self, bar: T):
        self.bar: T = bar


class Child(Base[T]):

    def __init__(self, bar: T):
        super().__init__(bar)

mypy 0.720 (on windows) says

> mypy.exe test\__init__.py
test\__init__.py:15: error: Argument 1 to "__init__" of "Base" has incompatible type "str"; expected "T"
test\__init__.py:15: error: Argument 1 to "__init__" of "Base" has incompatible type "int"; expected "T"

but if I change the T definition to T = typing.TypeVar('T') the errors go away

What I want is to specify that

  • the "Base" constructor has a parameter that could be an int or a str
  • the "Child" constructor has the same "signature" of the "Base" one (well, this is a simplified example, I want something more...)

is this a bug? di I misinterpreted the TypeVar usage?

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

Reproduce the example in test_init_.py with mypy 0.720, comparing the constrained TypeVar with the unconstrained version. Read the relevant generic and TypeVar-checking paths, then establish whether the reported diagnostic is expected; done means documenting the behavior or adding a regression test and correcting it if it is a bug.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
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.