Skip to content

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

@gh-andre

Description

@gh-andre

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions