list comprehensions: mypy fails to derive the union type for lists but not for tuples
Open
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
Inside a list comprehension mypy fails to derive the union type for lists but not for tuples.
To Reproduce
a = 5
b = "a_string"
list1: list[int | str] = [x for x in (a, b)] # works
list2: list[int | str] = [x for x in [a, b]] # fails
Expected Behavior
The same type should be derived for both lists.
Actual Behavior
The first list is recognised as list[int | str],
The second list is recognised as list[object],
Hence the error on line 4
❯ mypy mypy-repro.py ─╯
mypy-repro.py:4: error: List comprehension has incompatible type List[object]; expected List[int | str] [misc]
Found 1 error in 1 file (checked 1 source file)
Your Environment
❯ python --version ─╯
Python 3.11.8
❯ pip list | grep mypy ─╯
mypy 1.13.0
mypy-extensions 1.0.0
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 by running the provided Python 3.11.8 reproduction with mypy 1.13.0 and compare inference for the tuple and list expressions. Trace list-comprehension type inference and add or update a regression test so both expressions derive the same list[int | str] 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
- 45/100