Skip to content

list comprehensions: mypy fails to derive the union type for lists but not for tuples #18072

@anilbey

Description

@anilbey

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-join-v-unionUsing join vs. using unions

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions