python / python/mypy

Type of argument is not inferred for a TypeVar in a Generic type

Open
#5,324 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

documentation priority-1-normal topic-type-variables topic-usability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Mypy needs a type annotation for a variable that it could easily infer from the constructor argument annotations. This works perfectly with normal types. But using a TypeVar in a Generic type, somehow it doesn't.

from typing import Generic, TypeVar


class A:
    pass


class B:
    pass


T_Value = TypeVar("T_Value", A, B)


class Guess(Generic[T_Value]):
    def __init__(self, value: T_Value, confidence: float) -> None:
        self.value = value  # <-- line 17
        self.confidence = confidence

Mypy then complains it needs a type annotation

foo.py:17: error: Need type annotation for 'value'

This of course is no big deal since I can just add that annotation:

class Guess(Generic[T_Value]):
    def __init__(self, value: T_Value, confidence: float) -> None:
        self.value: T_Value = value
        self.confidence = confidence

But shouldn't mypy infer the type from the type annotations in the constructor?

If I'm doing something wrong please let me now.
I didn't find a similar issue but if this is a duplicate feel free to close.

I'm using:
Python 3.7.0, mypy 0.610, macOS 10.13.5

Same result with the current master (2018-07-05):
mypy 0.620+dev-f5058bcb269a55b33a02c3e3fd345541839bf06e

Flags I'm using:
strict_optional = true
ignore_missing_imports = true
follow_imports = silent

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 inline Python example with the reported strict_optional, ignore_missing_imports, and follow_imports settings. Start by tracing mypy's inference for the Generic TypeVar attribute assignment; done means the example no longer requires an explicit annotation and the behavior is covered by a regression test.

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.