mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Using isinstance in generic function causes spurious type error

Open brianm78 opened this issue 3 years ago • 1 comments

Bug Report

When using an isinstance check in a generic function/class, mypy infers the type as being the checked type, overriding the knowledge that it's also the generic type, leading to type errors even if the check is only relevant when T could include that type.

To Reproduce

See https://mypy-play.net/?mypy=latest&python=3.11&gist=4eb527cbef6cebc403b3d6bb3fae3873

Here, returning the value in an isinstance(x, str) check (or outside the reverse check) will cause error: error: Incompatible return value type (got "str", expected "T")

Interestingly, replacing return in the not isinstance(x, str) check with pass causes it to typecheck with no issues, even though the exact same code path will be taken for values not of that type.

Expected Behavior

I wouldn't have expected any of the functions in the gist to raise type errors - it doesn't seem like an isinstance check should override the known type being T.

Actual Behavior

Mypy generates errors for two of the functions:

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

Your Environment

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

brianm78 avatar Jun 05 '23 17:06 brianm78

Duplicate of e.g. #15151

hauntsaninja avatar Jun 05 '23 21:06 hauntsaninja