Skip to content

Commit a66a415

Browse files
SONARPY-778 Fix FPs for TypedDict on S5890 (SonarSource#848)
1 parent d0e4e23 commit a66a415

2 files changed

Lines changed: 16 additions & 1 deletion

File tree

python-checks/src/main/java/org/sonar/python/checks/InconsistentTypeHintCheck.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,10 @@ private static void checkAnnotatedAssignment(SubscriptionContext ctx, AnnotatedA
5252
InferredType inferredType = assignedExpression.type();
5353
TypeAnnotation annotation = annotatedAssignment.annotation();
5454
InferredType expectedType = InferredTypes.fromTypeAnnotation(annotation);
55+
if (expectedType.mustBeOrExtend("typing.TypedDict")) {
56+
// Avoid FPs for TypedDict
57+
return;
58+
}
5559
if (!inferredType.isCompatibleWith(expectedType) || isTypeUsedInsteadOfInstance(assignedExpression, expectedType)) {
5660
String inferredTypeName = InferredTypes.typeName(inferredType);
5761
String inferredTypeNameMessage = inferredTypeName != null ? String.format(" instead of \"%s\"", inferredTypeName) : "";

python-checks/src/test/resources/checks/inconsistentTypeHint.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import SupportsFloat, List, Iterable, Generator, Set, Union, Type
1+
from typing import SupportsFloat, List, Iterable, Generator, Set, Union, Type, TypedDict
22

33
def assigned_directly():
44
my_int_nok: int = "hello" # Noncompliant {{Assign to "my_int_nok" a value of type "int" instead of "str" or update its type hint.}}
@@ -107,3 +107,14 @@ def metaclasses():
107107
def a_function(): ...
108108
another_var: Type = a_function # Accepted FN
109109
another_var: Type = unknown_symbol
110+
111+
def type_dict():
112+
class MyCustomDict(TypedDict):
113+
user_ids: Set[int]
114+
message_ids: Set[int]
115+
116+
def my_dict() -> MyCustomDict:
117+
users = {1,2,3}
118+
messages = {1,2,3}
119+
my_dict: MyCustomDict = dict(user_ids=users, message_ids=messages) # OK
120+
return my_dict

0 commit comments

Comments
 (0)