python / python/mypy

Bad self type inference with Generics and inheritance?

Open
#9,322 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug priority-2-low
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

  • Are you reporting a bug, or opening a feature request?

Reporting a bug

  • Please insert below the code you are checking with mypy
from typing import TypeVar, Generic

T = TypeVar("T")

class Foo(Generic[T]):
    def __init__(self): ...

class Bar(Generic[T]): ...

class FooChild(Foo[Bar[T]]):
    def __init__(self, blah: T):
        Foo.__init__(self)
  • What is the actual behavior/output?
$ mypy foo.py
foo.py:18: error: Argument 1 to "__init__" has incompatible type "FooChild[T]"; expected "Foo[T]"
Found 1 error in 1 file (checked 1 source file)
  • What is the behavior/output you expect?
Success: no issues found in 1 source file
  • What are the versions of mypy and Python you are using?
mypy 0.750
Python 3.7.3
  • Do you see the same issue after installing mypy from Git master?

Yes, successfully reproduced with mypy 0.790+dev.df6894b5a9bb1a913e66df87138cd7a240c09fc1

  • What are the mypy flags you are using? (For example --strict-optional)

No flags.

  • If mypy crashed with a traceback, please paste
    the full traceback below.

No crash

  • Additional information:

The following versions typecheck successfully:

from typing import TypeVar, Generic

T = TypeVar("T")

class Foo(Generic[T]):
    def __init__(self): ...

class Bar(Generic[T]): ...

class FooChild(Foo[T]): # Removed one level of nesting here
    def __init__(self, blah: T):
        Foo.__init__(self)
from typing import TypeVar, Generic

T = TypeVar("T")

class Foo(Generic[T]):
    def __init__(self): ...

class Bar(Generic[T]): ...

class FooChild(Foo[Bar[T]]):
    def __init__(self): # Removed the argument here
        Foo.__init__(self)

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 supplied foo.py reproducer and run it against the reported mypy versions, confirming the incorrect self type for FooChild[T]. Trace the generic inheritance and constructor call involved in mypy's type inference, then add coverage showing that the nested Bar[T] case succeeds without errors.

Written by the indexing model from the issue text.

Assessment

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