Skip to content

Using isinstance in generic function causes spurious type error #15373

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
brianm78 opened this issue Jun 5, 2023 · 1 comment
Closed

Using isinstance in generic function causes spurious type error #15373

brianm78 opened this issue Jun 5, 2023 · 1 comment
Labels
bug mypy got something wrong

Comments

@brianm78
Copy link

brianm78 commented Jun 5, 2023

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 brianm78 added the bug mypy got something wrong label Jun 5, 2023
@hauntsaninja
Copy link
Collaborator

Duplicate of e.g. #15151

@hauntsaninja hauntsaninja closed this as not planned Won't fix, can't repro, duplicate, stale Jun 5, 2023
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