Bug: New python:S1854 rule is confused by type annotation

S1854 gets triggered in when variables are declared for type annotation purposes.

For example this code is perfectly valid and needed to add type annotation:

foo: Set[str, ...]
if x is None:
    foo = ('a', 'b')
    [ ... ]
    foo = get_a_set(y)

bar: str
for bar in get_some_strings():
    [ ... ]

The rule should detect that the type assignment lines are pure type declarations and not assignments per say. This format is necessary as doing the type annotation inside the if/else block would require repetition of the types, which would be inappropriate. In the second case the type assignment cannot be done inside the for loop declaration and has to be done ahead of it.

Relevant sections of PEP 526:

That’s indeed a false positive.
I created SONARPY-510 to track it.

Thanks a lot for the feedback!

Hi @sodul,
FYI, we’ve just released SonarPython 2.2 that should fix the reported False Positive.

Thank you again for your contribution!

Thanks @Andrea_Guarino, we’ll look for it in SonarCloud.