Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does mypy complain about my dictionary comprehension?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading