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
{{ message }}
Repository navigation
[1.18 regression] Negative type narrowing of TypeIs of Union with TypeVar not working #20330
When I use a TypeIs on a union of a TypeVar and something else (for example int), it seems the negative type narrowing does not work. mypy accepts it as safe in version 1.17.1, but fails since 1.18.1.
In my stack overflow question about this, a commenter said this was changed in #18193 and they suspect it to be a bug. I don't know if it is a bug, however the code below sure looks safe to me.
To Reproduce
Check the following code with mypy, at least version 1.18.1 mypy playground
I can confirm that I still think this code is safe - please enlighten me if I misunderstand the TypeIs semantics, but this looks exactly like the intended use case of TypeIs. The TypeIs PEP does not provide any generic examples, and neither does the spec.
Btw, my initial guess that we can't synthesise the intersection due to missing upper bound was wrong, the problem persists even with _T = TypeVar('_T', bound=str).
Bisects to #18193, cc @brianschubert - please confirm that this issue is valid, I might be missing some unsafe behavior here!
@sterliakov thanks for the ping! I don't have the time to think about this too deeply now, but at a glance I'd say this seems valid. It wasn't something I thought about in #18193
changed the title [-]Negative type narrowing of `TypeIs` of Union with `TypeVar` not working[/-][+][1.18 regression] Negative type narrowing of `TypeIs` of Union with `TypeVar` not working[/+]on Nov 29, 2025
Activity
sterliakov commentedon Nov 29, 2025
I can confirm that I still think this code is safe - please enlighten me if I misunderstand the
TypeIssemantics, but this looks exactly like the intended use case ofTypeIs. The TypeIs PEP does not provide any generic examples, and neither does the spec.Btw, my initial guess that we can't synthesise the intersection due to missing upper bound was wrong, the problem persists even with
_T = TypeVar('_T', bound=str).Bisects to #18193, cc @brianschubert - please confirm that this issue is valid, I might be missing some unsafe behavior here!
brianschubert commentedon Nov 29, 2025
@sterliakov thanks for the ping! I don't have the time to think about this too deeply now, but at a glance I'd say this seems valid. It wasn't something I thought about in #18193
[-]Negative type narrowing of `TypeIs` of Union with `TypeVar` not working[/-][+][1.18 regression] Negative type narrowing of `TypeIs` of Union with `TypeVar` not working[/+]Fix narrowing for unions (python#20728)