python / python/mypy

[Bug] Using `filter` in `itertools.chain` makes them both infer wrong types.

Open
#8,226 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-inference topic-join-v-union
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Repro:

import itertools
from typing import List

x: List[int] = [1, 2, 3]
y: List[str] = ["  ", "", "abc"]


it = itertools.chain(x, filter(lambda s: s.strip() == "", y))
reveal_type(it)

Actual output:

main.py:8: error: "object" has no attribute "strip"
main.py:9: note: Revealed type is 'itertools.chain[builtins.object*]'

Expected output:
I was expecting no errors and didn't expect filter to be affected by what it is put in, i.e. if you put filter call separate from itertools.chain, it prevents the first errors about missing strip attr:

f = filter(lambda s: s.strip() == "", y)
it = itertools.chain(x, f)
reveal_type(it)

The revealed type is still wrong though.


Python version: 3.7.6
Mypy version: 0.760 (still occurs on master)
Used flags: --strict

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 supplied example with mypy 0.760 or current master under --strict, comparing the inline and separate filter forms. The payload names no source files or tests; done means the inline form reports no missing strip attribute and reveals an appropriate chain element type rather than object.

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.