Skip to content

False positive when assigning bounded generic to union including the bound #20516

@randolf-scholz

Description

@randolf-scholz

The following example is type-safe, but mypy reports 6 false positives:

def upcast(arg: int) -> int:
    return arg

def test[X: int](items: list[X]) -> list[X]:
    _a: list[int] = list(items)           # ✅️
    _b: list[int] = [*items]              # ✅️
    _c: list[int] = [x for x in items]    # ✅️

    _1: list[str] | list[int] = list(items)         # ❌️
    _2: list[int] | list[str] = list(items)         # ❌️
    _3: list[str] | list[int] = [*items]            # ❌️
    _4: list[int] | list[str] = [*items]            # ❌️
    _5: list[str] | list[int] = [x for x in items]  # ❌️
    _6: list[int] | list[str] = [x for x in items]  # ❌️
    _7: list[str] | list[int] = [upcast(x) for x in items]  # ✅️
    _8: list[int] | list[str] = [upcast(x) for x in items]  # ✅️
    return items

context: #20419 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions