S5655 & S5890 FP: dict literal not recognized as Mapping

Python 3.9

In the following code sample, SonarLint reports violations of S5655 (Arguments given to functions should be of an expected type) and S5890 (Values assigned to variables should match their type annotations) in the lines marked with the comment FP:

from collections.abc import Mapping
from typing import Any

def f(mapping: Mapping[str, Any]) -> dict[str, Any]:
    return dict(mapping)

f({"a": 2})  # FP S5655

d1: Mapping[str, Any] = {"a": 2}  # FP S5890

d2: dict[str, Any] = {"a": 2}

d3 = {"a": 2}

dict is an instance of collections.abc.Mapping and all keys of the dicts used here are strings, therefore all dict literals here are instances of Mapping[str, Any] and, in consequence, all assignments should pass.

Since both assignments of d2 and d3 as well as the function calls f(d2) and f(d3) pass the check, the FP seems to be triggered only when a dict literal is assigned to a variable or parameter declared as a Mapping[str, Any].

Hi @ludwigc ,

Thanks a lot for reporting those false positives. I created SONARPY-998 to keep track of them.

In the meanwhile, as a workaround, I suggest adding sonar.python.version: "3.9" into SonarLint analyzer properties. This should solve your FPs.

Also, make sure to restart your IDE after setting this property so that it will be taken into account by SonarLint.

Hope that helps,

Thanks, @Andrea_Guarino,

explicitly specifying the Python version in the analyzer properties does indeed fix the FPs.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.