Skip to content

Dict values not inferred correctly with .get() calls #6258

@davidbauer99

Description

@davidbauer99

The function below results in an unexpected return type error. test.py:6: error: Incompatible return value type (got "Optional[int]", expected "int")

from typing import Dict


def results_in_error(data: Dict[str, int], key: str) -> int:
    if key in data:
        return data.get(key)
    return 0


def works_as_expected(data: Dict[str, int], key: str) -> int:
    val = data.get(key)
    if val:
        return val
    return 0

Replacing if key in data: with if data.get(key): will result in an identical error.

My mypy.ini file is the following:

[mypy]
ignore_missing_imports=True
python_version = 3.6
strict_optional=True
check_untyped_defs=True
disallow_untyped_calls=True
disallow_untyped_defs=True
follow_imports=normal
follow_imports_for_stubs=True

I believe this is a false positive as the value will not be None due to the dict's typing.

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