Uploaded image for project: 'SonarPython'
  1. SonarPython
  2. SONARPY-532

Support assignment expression syntax (Python 3.8)

    XMLWordPrintable

    Details

    • Type: New Feature
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 2.8
    • Component/s: Parser
    • Labels:
      None

      Description

      Python 3.8 introduces the possibility to assign to variables within a larger expression.

      Example: 

      if (n := len(a)) > 10: 
          print(f"List is too long ({n} elements, expected <= 10)")
      

      To support this new syntax, we need to:

      • Update the parser
      • Update the Symbol Table (SONARPY-621)
      • Update sonar-security uCFG (related SonarSecurity ticket: SONARSEC-921)

      Rule indirectly impacted (through symbol table):

      • RSPEC-1481: Unused local variables should be removed

      RSPEC-3827 should also be checked to behave correctly with the following change:

      • Dict comprehensions have been synced-up with dict literals so that the key is computed first and the value second. The guaranteed execution order is helpful with assignment expressions because variables assigned in the key expression will be available in the value expression.

      So that the following code snippet doesn't raise any false positive:

      a = 41
      dict = {(s := a + 1) : s}
      

      This code however should raise an issue as s is not yet defined when the key is evaluated:

      a = 41
      dict = {s: (s := a + 1)}
      

      RSPEC-3516 should be checked to correctly raise issues on cases such as:

      def identifiers(a, b):
          if (b := 12) == a:
              return b
          else:
              return b  # Noncompliant
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              guillaume.dequenne Guillaume Dequenne
              Reporter:
              guillaume.dequenne Guillaume Dequenne
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Due:
                Created:
                Updated:
                Resolved: