mypy icon indicating copy to clipboard operation
mypy copied to clipboard

(🐞) `isinstance` with generic type narrows the generic parameters to `Any` when it should narrow to a safe type

Open KotlinIsland opened this issue 3 years ago • 1 comments

a: object
if isinstance(a, list):
    reveal_type(a) # list[Any]
    b = a[0] # Any

Why is a narrowed to list[Any]? It should be narrowed to list[T_co] where T_co = TypeVar("T_co", covariant=True)

related: #12015

also:

i: Iterable[int]
assert isinstance(i, list):
reveal_type(i) # list[Any]

KotlinIsland avatar Feb 08 '22 01:02 KotlinIsland

I noticed this issue is impacting the mypy codebase to some extend:

# mypy.types.CallableArgument
    def accept(self, visitor: "TypeVisitor[T]") -> T:
        assert isinstance(visitor, SyntheticTypeVisitor)
        return visitor.visit_callable_argument(self)  # Revealed type is Any

KotlinIsland avatar Aug 09 '22 08:08 KotlinIsland