Why does mypy complain about my dictionary comprehension?

Question:

I’m trying to do an update of a dictionary with a dictionary comprehension. My code works fine, but mypy raises an error while parsing the types.

Here’s the code:

load_result = {"load_code": "something"}
load_result.update({
    quality_result.quality_code: [quality_result.quantity]
    for quality_result in random_quality_results()
})

In that code the quality_result objects have those two attributes quality_code and quantity which are a string and a float respectively.

Here the code for those quality result objects:

class QualityResult(BaseSchema):
    """Asset quality score schema."""

    quality_code: str
    quantity: float = Field(
        ...,
        description="Value obtained [0,1]",
        ge=0,
        le=1,
    )

My code works as expected and returns the desired dictionary, but when running mypy it throws this error:

error: Value expression in dictionary comprehension has incompatible type "List[float]"; expected type "str"

I see mypy is getting the types correctly as I’m inserting a list of floats, the thing is I don’t understand why it complains. I assume I must be missing something, but I’m not being able to figure it out.

Why does it say it must be a string? How can I fix it?

Asked By: aarcas

||

Answers:

On the first line you write:

load_result = {"load_code": load}

load is a string and this code makes mypy assume that the type for load_result is going to be Dict[str, str]. Then later on you write you dictionary comprehension where your values are of type List[float].

Depending on what values you want in your dictionary, you can explicitly type it on the first line:

load_result: Dict[str, Union[str, List[float]]] = {"load_code": load}

or

load_result: Dict[str, Any] = {"load_code": load}
Answered By: Rehan Rajput
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.