python / python/mypy

Incorrect resolution of `type[TypeVar]` returning `TypeVar` with `numpy`

Open
#20,354 7 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

This came up with pandas-stubs, but can reproduce with just numpy

To Reproduce

from typing import TypeVar
import numpy as np

NDArrayT = TypeVar("NDArrayT", bound=np.ndarray)


def foo(x: type[NDArrayT]) -> NDArrayT:
    return x([1, 2])


reveal_type(foo(np.ndarray))

Expected Behavior

Revealed type should be ndarray[tuple[Any, ...], dtype[Any]], which is what pyright reports.

Actual Behavior

mypy reports numpy.ndarray[Any, Any]

Your Environment

  • Mypy version used: 1.19.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.11
  • numpy version: 2.3.5
  • pyright version: 1.1.407

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 by running the provided Python reproduction with mypy 1.19.0 and compare its revealed type with pyright's result. Trace the type inference for type[TypeVar] and ndarray, then add a regression test showing that foo(np.ndarray) reveals the expected ndarray type.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.