Skip to content

Misleading type inference on complicated dict literal #8277

@alanhdu

Description

@alanhdu

This might not be a "bug" per se, but I'm going to report it anyways in case.

Running mypy 0.761 on Python 3.6 on the following code

def get_api_message(a: str, b: str, c: int, d: str) -> None:
    api_message = {
        "d": d,
        "api_request": {"c": c, "start_stream_request": {"b": b, a: {}}},
    }
    reveal_type(api_message)

gives us a revealed type of:

$ mypy scratch.py
Revealed type is 'builtins.dict[builtins.str*, typing.Collection*[builtins.str]]'

This led to a confusing error downstream where code that edits part of the dict literal gets a Value of type "Collection[str]" is not indexable.

I get why Collection is being inferred, but probably in this case it'd be better to either explicitly require a type annotation or to infer Dict[str, Any] instead.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions