Skip to content

No type inference for indexed expressions #3006

Closed
@pkch

Description

@pkch

I'm sure there's a limit to how far type inference can go, and it's reasonable that it doesn't evaluate the result of applying an index:

from typing import *

def f(x: Dict[str, Union[int, str]], k: str) -> None:
    if isinstance(x[k], int):
        x[k] + 1  # type error: Unsupported operand types for + ("Union[int, str]" and "int")

But maybe an example in the docs would be helpful? A suggestion could be given to either rewrite it like this:

def f(x: Dict[str, Union[int, str]], k: str) -> None:
    v = x[k]
    # note: both x[k] (in the if expression and in the body) must be replaced with a simple variable
    if isinstance(v, int):
        v + 1  # no type error

or to just mark it as # type: ignore.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions