Skip to content

Recognize isinstance(a[b], ...)? #2458

Closed
@JukkaL

Description

@JukkaL

Consider this fragment:

from typing import Union, Dict

x = {}  # type: Dict[str, Union[int, str]]
n = ''
if isinstance(x[n], int):
    reveal_type(x[n])  # E: Revealed type is 'Union[builtins.int, builtins.str]'

Perhaps mypy should infer type int for x[n] (i.e. put x[n] into the conditional type binder).

The example can be refactored to type check pretty easily:

...
t = x[n]
if isinstance(t, int):
    ...

A slightly more interesting example that is a bit harder to get to type check:

...
if n in x and isinstance(x[n], int):
    ...

This was originally reported by @davire on gitter.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions