Skip to content

Ternary operator + isinstance + typevar confuses mypy #11111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
098799 opened this issue Sep 15, 2021 · 2 comments
Closed

Ternary operator + isinstance + typevar confuses mypy #11111

098799 opened this issue Sep 15, 2021 · 2 comments
Labels
bug mypy got something wrong topic-ternary-expression a if b else c

Comments

@098799
Copy link

098799 commented Sep 15, 2021

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
@098799 098799 added the bug mypy got something wrong label Sep 15, 2021
@stevenh
Copy link

stevenh commented Jan 11, 2024

Tripped over this as its a rule that ruff enforces by default, putting it in conflict with mypy.

Ended up using # noqa: SIM108 to disable the ruff rule until this is fixed.

Tested with mypy: 1.8.0

@brianschubert
Copy link
Collaborator

Thanks for the report! Closing as duplicate of #4134

@brianschubert brianschubert closed this as not planned Won't fix, can't repro, duplicate, stale Dec 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-ternary-expression a if b else c
Projects
None yet
Development

No branches or pull requests

4 participants