Skip to content

Type narrowing of 'TypeVar' causes '[return-value]' error #15151

Closed
@nikitagashkov

Description

@nikitagashkov

Bug Report

mypy reports a type incompatibility error when the TypeVars are narrowed within a generic function but the generic arg is not changed in any way.

To Reproduce

from typing import TypeVar

T = TypeVar("T")


def foo(v: T) -> T:
    if isinstance(v, str):
        return v  # error: Incompatible return value type (got "str", expected "T")  [return-value]
    return v

…and a mypy-play link.

Expected Behavior

No errors are thrown since the variable wasn't patched in any way (e.g., it was not returned as str(v)).

Actual Behavior

main.py:8: error: Incompatible return value type (got "str", expected "T")  [return-value]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.2.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions