Skip to content

False positive when using ternary statement #19998

@ngnpope

Description

@ngnpope

Bug Report

When using tuple() or next() on a generator in a ternary statement with a simple boolean flag to switch, a false positive is raised. This doesn't happen when not using a ternary statement.

To Reproduce

from pathlib import Path


def good(path: Path, *, multiple: bool = False) -> Path | tuple[Path, ...]:
    paths = path.glob("*.txt")
    if multiple:
        return tuple(paths)
    return next(paths)


def bad(path: Path, *, multiple: bool = False) -> Path | tuple[Path, ...]:
    paths = path.glob("*.txt")
    return tuple(paths) if multiple else next(paths)

https://mypy-play.net/?mypy=latest&python=3.12&gist=d679746319e70a4455c073ba187eac89

Expected Behavior

No errors raised.

Actual Behavior

$ mypy --strict bug.py
bug.py:13: error: Argument 1 to "next" has incompatible type "Generator[Path, None, None]"; expected "SupportsNext[tuple[Path, ...]]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.18.2
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12, 3.13

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-contextType context / bidirectional inference

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions