False positive on python:S3827 with function type parameters

  • What language is this for? Python 3.12
  • Which rule? S3827
  • Why do you believe it’s a false-positive/false-negative? it complies with PEP-695 and mypy has no complaints
  • SonarQube Server / Community Build - which version? self-hosted, Developer Edition v10.7
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
def sum_them[T](values: list[T]) -> T | None:
    if values:
        result: T = type(values[0])()
        return result
    return None

The inner usage of T as a type annotation on line 3 is necessary to trigger the false positive. This is also where the issue is reported.

You may need a test as well depending on your configuration. Here is the one that I used:

import unittest

import sample


class SampleTests(unittest.TestCase):
    def test_with_floats(self) -> None:
        self.assertEqual(sample.sum_them([0.1, 0.2, 0.3, 0.4]), 0.0)

    def test_with_ints(self) -> None:
        self.assertEqual(sample.sum_them([1, 2, 3]), 0)

    def test_with_strings(self) -> None:
        self.assertEqual(sample.sum_them(['hello', ' ', 'world']), '')
1 Like

Hello @dave-shawley,
Thanks for your report.
This is indeed a false positive and stems from a bug in the python analyzer. When checking which local variables (including parameters) were never written to, no assignment can be found for T. Parameters, like values, are always treated as being assigned. Unfortunately, this isn’t the case for type parameters. Thus this bug.

I’ve created the following ticket SONARPY-2577 to track the work. It should be fairly simple to fix.

Best,
Sebastian Zumbrunn