python / python/mypy

Mypy fails to solve `tuple[int, *Ts, int]` as an `Iterable[T]`.

Open
#19,659 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

from typing import Iterable

def upcast[T](arg: Iterable[T]) -> Iterable[T]: return arg

def f[*Ts](padded_tuple: tuple[int, *Ts, int]) -> None:
    as_iterable = upcast(padded_tuple)  # Argument 1 to "upcast" has incompatible type
    reveal_type(as_iterable)  # "typing.Iterable[builtins.int]" ❌

https://mypy-play.net/?mypy=latest&python=3.12&enable-incomplete-feature=PreciseTupleTypes&gist=ed0d06b3234441ebf6f31b98224618fc

For comparison, pyright predicts Code sample in pyright playground Iterable[int | Union[*Ts@demo]].

Since Union of TypeVarTuple is not specced yet, mypy should nevertheless probably fall back to something like Iterable[object] or Iterable[Any], but Iterable[int] is just wrong.

If the tuple is not padded, then mypy still falsely issues [arg-type], but at least the reveal_type is Iterable[Any]. https://mypy-play.net/?mypy=latest&python=3.12&enable-incomplete-feature=PreciseTupleTypes&gist=b3429973142b9a329d0fcc1dda8aabb2

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 reproductions and compare the padded and unpadded tuple cases. Trace TypeVarTuple inference for the Iterable[T] call and verify the result against the reported pyright behavior; done means no incorrect arg-type error and no falsely narrowed Iterable[int] type.

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
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.