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

A constrained TypeVar value fails type() narrowing tests #18428

Open
gh-andre opened this issue Jan 7, 2025 · 0 comments
Open

A constrained TypeVar value fails type() narrowing tests #18428

gh-andre opened this issue Jan 7, 2025 · 0 comments
Labels
bug mypy got something wrong

Comments

@gh-andre
Copy link

gh-andre commented Jan 7, 2025

Bug Report

When a TypeVar is constrained, passing a value of the constrained type into type() fails narrowing tests.

To Reproduce

from typing import TypeVar

W = TypeVar("W", int, str)

def fn(w: W) -> W:
    if type(w) is str:
        # main.py:30: note: Revealed type is "builtins.int"
        # main.py:30: note: Revealed type is "builtins.str"
        reveal_type(w)

        # reports error:
        # main.py:31: error: Incompatible types in assignment (expression has type "int", variable has type "str")  [assignment]
        s: str = w
        print("s: %s" % s)

    elif type(w) is int:
        # same in this block
        reveal_type(w)
        i: int = w
        print("s: %d" % i)
        
    return w

If I change W to use binding, the problem goes away. That is, if I use this, no errors are reported.

W = TypeVar("W", bound=int|str)

Testing the original code in Pyright does not report any problems.

Using isinstance() makes it work for class types in general, but cannot be used against TypedDict instances and where a specific class type is required.

Expected Behavior

The condition type(w) is str should narrow w to have str in its conditional block.

Actual Behavior

These errors are reported:

main.py:35: error: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment]
main.py:44: error: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment]

Your Environment

This is not environment specific and I can reproduce the same on Windows or Linux.

  • Mypy version used: 1.14.1
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10
@gh-andre gh-andre added the bug mypy got something wrong label Jan 7, 2025
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

1 participant