Skip to content
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

Parameters of the form type[typevar] cause issues with type refinement #18277

Closed
Pluviolithic opened this issue Dec 10, 2024 · 2 comments
Closed
Labels
bug mypy got something wrong

Comments

@Pluviolithic
Copy link

When defining a function with the type of a TypeVar as one of the parameters and a return value of that same TypeVar, Mypy incorrectly traverses type refinement branches and throws an incompatible return value type error.

To Reproduce

Example A
Related variant Example B
Example C

Example A at-a-glance:

from typing import TypeVar, reveal_type

Test = TypeVar(
    "Test", int, str, bool
)

def get_test(t: type[Test]) -> Test:
    if isinstance(t, int):
        reveal_type(t)
        return 1
    elif isinstance(t, str):
        reveal_type(t)
        return "asdf"
    else:
        reveal_type(t)
        return True

Expected Behavior

I do not expect mypy to identify issues with the code. Even though the types are narrowed, they still return correctly in conjunction with what is passed in for t, which I believe to be technically correct.

Actual Behavior

main.py:15: note: Revealed type is "type[builtins.int]"
main.py:15: note: Revealed type is "type[builtins.str]"
main.py:15: note: Revealed type is "type[builtins.bool]"
main.py:16: error: Incompatible return value type (got "bool", expected "str")  [return-value]
Found 1 error in 1 file (checked 1 source file)

Workaround

A simple workaround is to just wrap the return value with a call to t. Playground example here. Even though the workaround is "simple," code modifications like this shouldn't be necessary to use a typechecker.

Environment

  • Mypy version used: 1.13.0
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12
@Pluviolithic Pluviolithic added the bug mypy got something wrong label Dec 10, 2024
@brianschubert
Copy link
Collaborator

Closing per the explanation given at microsoft/pyright#9568 (comment).

Also note that bool is a subclass of int. You should probably check for bool before int case in the fixed code to avoid taking the int branch in both cases.

@brianschubert brianschubert closed this as not planned Won't fix, can't repro, duplicate, stale Dec 10, 2024
@Pluviolithic
Copy link
Author

Appreciate it, thanks.

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