python / python/mypy

Faulty type narrowing with value restrictions

Open
#13,083 0 comments 0 reactions 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

Bug Report

When passing an empty list directly into a value restricted generic function, the inferred return type can end up being too narrow.

To Reproduce

from typing import TypeVar


TV = TypeVar("TV", str, int)


def foo(x: list[TV]) -> list[TV]:
    return x
    

# Should be: builtins.list[builtins.str] | builtins.list[builtins.int]
reveal_type(foo([]))  # "builtins.list[builtins.str]"

https://mypy-play.net/?mypy=latest&python=3.10&flags=strict&gist=129ba2fed0c6ba1a861149f944db3420

Expected Behavior

I would expect the revealed type to either be builtins.list[builtins.str] | builtins.list[builtins.int].

Alternatively, having this result in an error of some sort would be fine. As a reference, when assigning the empty list first, it becomes a list[Any] instead of a list[<nothing>]. This results in the revealed type being list[Any], but also an error along the lines of Need type annotation for "l" (hint: "l: List[<type>] = ...").

Actual Behavior

The revealed type was builtins.list[builtins.str]

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 reproducer and trace handling of empty list arguments with value-restricted TypeVar inference. Compare the inferred type with the expected union and the acceptable diagnostic behavior described in the issue. Done means the example no longer narrows incorrectly to list[str].

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.