8000 `TypeVar` bound to `Union` in `if isinstance(...)` branch has incompatible return type · Issue #12800 · python/mypy · GitHub
[go: up one dir, main page]

Skip to c 8000 ontent
TypeVar bound to Union in if isinstance(...) branch has incompatible return type #12800
Closed as not planned
@headtr1ck

Description

@headtr1ck

Bug Report

A TypeVar bound to Union[x, y] will resolve to x after an if isinstance(..., x) is used which is incompatible with the return type.

I'm not sure on how to describe exactly what is going on, better check the Example.
Also mypy experts, please forgive me if that is intended behavior and not a bug (I would appreciate a working solution in this case :)

To Reproduce

Example:

from typing import TypeVar, Union

T = TypeVar("T", bound=Union[str, int])

def a(x: T) -> T:
    if isinstance(x, str):
        return x
    return x

Expected Behavior

I expect that this definition is correct, since whatever input is given, the output is the same.

Actual Behavior

mypy raises error: Incompatible return value type (got "str", expected "T").

Further Info

  • I want to have the str -> str, int -> int mapping, so simply using Union[str, int] won't work.
  • This function is called sometimes with variables of type Union[str, int], so using TypeVar("T", str, int) won't work either.

Your Environment

  • Mypy version used: 0.950
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.9
  • Operating system and version: win10

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0