Skip to content

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

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
mgab opened this issue Feb 11, 2025 · 1 comment
Labels
bug mypy got something wrong

Comments

@mgab
Copy link

mgab commented Feb 11, 2025

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
@mgab mgab added the bug mypy got something wrong label Feb 11, 2025
@mgab
Copy link
Author

mgab commented Feb 11, 2025

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
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

2 participants