python / python/mypy

Looses type of nested/inner collection in a `flatten(filter(...))` chain

Open
#9,176 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

In the following, very reduced code line d does not typecheck.

from itertools import chain
from typing import List


ints_of_ints: List[List[int]]
c = filter(lambda ints: len(ints), ints_of_ints)  # ok
reveal_type(c)  # typing.Iterator[builtins.list[builtins.int]]

d = chain.from_iterable(filter(lambda ints: len(ints), ints_of_ints))  # mypy: error arg-type - Argument 1 to "len" has incompatible type
                                                                       # "Iterable[int]"; expected "Sized"
reveal_type(d)  # typing.Iterator[builtins.int*]

The interesting or surprising part is that inside the d line mypy thinks that ints is Iterable[int].

Tried mypy 0.782 and mypy-0.790+dev.4cf246f3bb2589d343fe1fdb67a42a23a23c041b.dirty

image

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 reproducing the reduced Python example with the reported mypy versions and inspect how type inference handles the filter callback inside chain.from_iterable. Done means the example typechecks and the revealed type for d remains Iterator[int] without weakening the behavior of the simpler filter case.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.