Skip to content

Ternary operator + isinstance + typevar confuses mypy #11111

Closed as not planned
Closed as not planned
@098799

Description

@098799

Bug Report

Two different results depending on whether a ternary operator or a simple if-else block is used.

To Reproduce

from typing import TypeVar


def handle_str(arg: str) -> str:
    return arg


def handle_list(arg: list) -> list:
    return arg


type_arg = TypeVar('type_arg', str, list[str])


def chooser__standard(arg: type_arg) -> type_arg:
    if isinstance(arg, str):
        return handle_str(arg)
    else:
        return handle_list(arg)


def chooser__ternary(arg: type_arg) -> type_arg:
    return handle_str(arg) if isinstance(arg, str) else handle_list(arg)

raises errors only in the second case.

Expected Behavior

No error in the ternary case. (Well, would be amazing to have singledispatch handle this so I don't have to write code like this, but that's not a discussion for here...)

Actual Behavior

playground.py:23: error: Argument 1 to "handle_str" has incompatible type "List[str]"; expected "str"
playground.py:23: error: Argument 1 to "handle_list" has incompatible type "str"; expected "List[Any]"

Your Environment

  • Mypy version used: mypy==0.910
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): ignore_missing_imports = True
  • Python version used: Python 3.9.6
  • Operating system and version: Manjaro Linux x86_64

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions