itertools.chain returns object when using iterators of different types
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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