You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When a TypeVar is constrained, passing a value of the constrained type into type() fails narrowing tests.
To Reproduce
fromtypingimportTypeVarW=TypeVar("W", int, str)
deffn(w: W) ->W:
iftype(w) isstr:
# 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=wprint("s: %s"%s)
eliftype(w) isint:
# same in this blockreveal_type(w)
i: int=wprint("s: %d"%i)
returnw
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
The text was updated successfully, but these errors were encountered:
Bug Report
When a
TypeVar
is constrained, passing a value of the constrained type intotype()
fails narrowing tests.To Reproduce
If I change
W
to 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 againstTypedDict
instances and where a specific class type is required.Expected Behavior
The condition
type(w) is str
should narroww
to havestr
in 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): noneThe text was updated successfully, but these errors were encountered: