python / python/mypy

(🐞) Generic Inference completely broken when a `TypeVar` has `None` in the `bound`

Open
#11,928 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

from typing import Generic, TypeVar, Iterable

T = TypeVar("T")
T1 = TypeVar("T1", bound=None)

class Test(Generic[T, T1]):
    def test(self) -> None:
        data1: list[T]
        data2: list[T] | list[T1]
        data3: list[T1] | list[T]
        
        reveal_type(tester(data1))  # list[T]
        reveal_type(tester(data2))  # list[object]
        reveal_type(tester(data3))  # list[Any]
        
        
def tester(a: Iterable[T]) -> list[T]: ...

The same thing happens if the bound is a union with None in it.

playground link

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 provided mypy-play playground link and run the minimal example under the stated Python 3.10 and strict settings. Compare the revealed types with the comments, then verify the same behavior for a union bound containing None; done means both cases infer the expected types.

Written by the indexing model from the issue text.

Assessment

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