Missing TypeIs narrowing with covariant generic
Open
Nobody has claimed this yet.
bug
topic-type-narrowing
topic-typeguard-typeis
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Mypy fails to narrow away an Any-specialized covariant generic after TypeIs narrowing to its object specialization:
from typing import Any, Generic, TypeVar
from typing_extensions import TypeIs
T_co = TypeVar("T_co", covariant=True)
class Source(Generic[T_co]): ...
def is_source(x: object) -> TypeIs[Source[object]]:
return False
def f(x: int | Source[Any]) -> None:
assert not is_source(x)
reveal_type(x) # expect int, mypy reveals int | Source[Any]
In contrast this does work correctly with an analogous contravariant type:
from typing import Any, Generic, TypeVar
from typing_extensions import Never, TypeIs
T_contra = TypeVar("T_contra", contravariant=True)
class Sink(Generic[T_contra]): ...
def is_sink(x: object) -> TypeIs[Sink[Never]]:
return False
def f(x: int | Sink[Any]) -> None:
assert not is_sink(x)
reveal_type(x) # int
(Found in python/typeshed#15931.)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Use the minimal Python snippet in the issue as the reproducer, then compare covariant Source[Any] narrowing with the working contravariant Sink[Never] case. Done means reveal_type(x) is int after assert not is_source(x), while preserving the existing Sink behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 50/100