python / python/mypy

Matching generic return type of `SupportsGetItem`

Open
#21,731 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

mypy does not match the generic return type of SupportsGetItem properly.

This was proposed in https://github.com/astral-sh/ty/issues/3988#issuecomment-4960290236.

To Reproduce

https://mypy-play.net/?gist=b8bb3085f195314a6c7c89ed2bdd2576

from __future__ import annotations

from typing import TYPE_CHECKING, Any, TypeVar

if TYPE_CHECKING:
    from _typeshed import SupportsGetItem

class Series: ...

class DataFrame:
    def __getitem__(self, key: object) -> Series:
        return Series()

T = TypeVar("T")

def f(x: SupportsGetItem[Any, T]) -> T:
    if isinstance(x, DataFrame):
        # return Series()
        return 1  # false error-free
    else:
        return x[0]

Expected Behaviour

Report an error about return type

Actual Behaviour

No error

Your Environment

mypy playground

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 linked mypy-play reproduction and inspect how SupportsGetItem[Any, T] is handled when control flow narrows x to DataFrame. Confirm the expected diagnostic from the example, then trace the relevant type-checking behavior and add or update coverage for this case. Done means mypy reports the invalid return type instead of accepting return 1.

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
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.