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
Bug Report
When a
TypeVaris constrained, passing a value of the constrained type intotype()fails narrowing tests.To Reproduce
If I change
Wto use binding, the problem goes away. That is, if I use this, no errors are reported.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 againstTypedDictinstances and where a specific class type is required.Expected Behavior
The condition
type(w) is strshould narrowwto havestrin its conditional block.Actual Behavior
These errors are reported:
Your Environment
This is not environment specific and I can reproduce the same on Windows or Linux.
mypy.ini(and other config files): none