Skip to content

False positive error on a generic type-preserving function if returning from within an isinstance branch #18658

Closed as duplicate

Description

@mgab

Bug Report

Mypy does not make deductions of the type of type parameter based on isinstance branches within the function. For example, in a function that takes an argument of any type and returns a value of that same type, it mypy raises an error about the type of the return argument not being correct if returning from within an isinstance branch.

To Reproduce

HERE IN THE PLAYGROUND

from typing import TypeVar

T = TypeVar("T")

def take_any_transform_only_str(obj: T) -> T:
    if isinstance(obj, str):
        # do stuff
        return obj
    return obj

Of course this example does not make much sense by itself, the idea would be to do some type-preserving transformations inside the isinstance branch

Expected Behavior

I'd expect this code annotations to validate without raising any error.

Actual Behavior

Raises the following error

main.py:8: error: Incompatible return value type (got "str", expected "T")  [return-value]

Your Environment

  • Mypy version used: 1.15.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.13.1

Activity

  1. added
    bugmypy got something wrong
    on Feb 11, 2025
  2. mgab commented on Feb 11, 2025

    @mgab
    Author

    Uops! Tried to find previously reported issues but didn't succeed, sorry for the duplicate! 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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