SonarQube and Python S2589 - False Positives

Must-share information (formatted with Markdown):

  • which versions are you using: SonarQube Enterprise v10.6
  • how is SonarQube deployed: Cloud (?). No idea.
  • what are you trying to achieve: To avoid incorrect SonarQube reports
  • what have you tried so far to achieve this: I don’t think there is much I can do…

Hello,

We’re using SonarQube through the cloud in our company to analyze Python code (Python 3.9).

My apologies if this issue has been reported somewhere else - I have searched the archives and I have seen it for other languages, but I couldn’t find anything specific to Python (but maybe it’s my lack of searching skills).

SonarQube insists on reporting incorrect issues related to Python - specifically pythonbugs:2589 (Boolean expressions should not be gratuitous) by returning this:

Fix this expression which always evaluates to “true”

Or this:

Fix this expression which always evaluates to “false”

This is a simplified example:

def example(param1, param2):
    if not param1 or (param1 and param2):
        print('Return True')
        return True

    print('Return False')
    return False

SonarQube tells me this:

image

However, running the simple function like this:

example(True, True)
example(False, True)
example(True, False)
example(False, False)

Does not always print Return True:

C:\XXXX\python.exe C:\YYYY\sonarqube_test.py 
Return True
Return True
Return False
Return True

I welcome any suggestion - and potential workarounds if you are aware of any of them. My knowledge of SonarQube is extremely limited. Thank you in advance.

Andrea.

Hi @infinity77 ,

Thanks for your reporting!

Inside the expression not param1 or (param1 and param2), the second instance of param1, when reached, will always be True (or to be precise a thruthy value in Python) because of short-circuit evaluation of boolean operators in Python (see the doc here). To say it differently, if param1 is False, then (param1 and param2) will never be evaluated.

The rule is flagging param1 in the boolean expression because the condition can be simplified to:

if not param1 or param2:

Apologies if the rule description and the issue reporting are not very clear on the expected fix!

Does that sound clearer?

Thank you for your reply and clarification - it does indeed help.

I was thrown off by the error message from SonarQube and I went looking to a completely wrong direction.

Thank you again, sorry for the noise/

1 Like