Skip to content

[1.19 regression] Ternary expression involving a union with Any evaluated as redundant #20445

@vfazio

Description

@vfazio

Bug Report

We recently ran into something in a canary pipeline with mypy 1.19 and it sounded related to #20363, but am making this issue separately per #20363 (comment)

It looks like Any or Awaitable may not always be type narrowed correctly when in a union and in a ternary expression?

To Reproduce

The following emits error: If condition is always true [redundant-expr]

from typing import Any, Awaitable
x: list[Any | Awaitable]

for y in x:
    z = 1 if isinstance(y, Awaitable) else 2

Changing the typing to drop Awaitable from the union:

from typing import Any, Awaitable
x: list[Any]

for y in x:
    z = 1 if isinstance(y, Awaitable) else 2

or typing the Awaitable generic to a specific type:

from typing import Any, Awaitable
x: list[Any|Awaitable[bool]]

for y in x:
    z = 1 if isinstance(y, Awaitable) else 2

or breaking up the ternary:

from typing import Any, Awaitable
x: list[Any | Awaitable]

for y in x:
    if isinstance(y, Awaitable):
        z = 1
    else:
        z = 2

resolves the error.

We did not see this in 1.18.x

Expected Behavior

In this case, I would expect there to be some differentiation between Any and Awaitable such that the conditional is not considered redundant

Your Environment

  • Mypy version used: 1.19.x
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files): redundant-expr
  • Python version used: 3.11+

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-reachabilityDetecting unreachable code

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions