python / python/mypy

itertools.chain returns object when using iterators of different types

Open
#17,915 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

I think this is related to the join-v-union discussion but this case is so easy to reproduce that I thought it's worth the ticket

To Reproduce

from itertools import chain

class A:
    def foo(self) -> None: ...

class B:
    def foo(self) -> None: ...


a_items = [A(), A()]
b_items = [B(), B()]

for item in chain(a_items, b_items):
    item.foo()

A workaround for this is to explicitly have an items: Iterator[A | B] = chain(...)

Expected Behavior

There shouldn't be any errors

Actual Behavior

chain.py:14: error: "object" has no attribute "foo"  [attr-defined]

Your Environment

$ mypy --version
mypy 1.11.2 (compiled: yes)
$ python --version
Python 3.12.3

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 reproduced example in chain.py and run it with mypy 1.11.2 to confirm the attr-defined error. Trace the typing and inference behavior for itertools.chain when its iterators contain different types; done means the loop item is inferred with a usable A | B type so item.foo() produces no error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 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.