terryyin / lizard

A simple code complexity analyser without caring about the C/C++ header files or Java imports, supports most of the popular languages.
Other
1.82k stars 248 forks source link

Python - Wrong Cyclomatic Complexity values #317

Open MarcW1g opened 3 years ago

MarcW1g commented 3 years ago

The following piece of code results in a wrong Cyclomatic Complexity value:

def testFunction(x):
    # this is a comment\
    if x > 10:
        return "Greater than 10"
    return "Lower"

The Cyclomatic Complexity of this method should be 2. However, the tool reports the CCN to be 1.

MarcW1g commented 3 years ago

Besides the issue with a line break at the end of a comment, there is also an error which occurs in combination with f-strings.

When you put any structure like a list comprehension or a one-line if inside a f-string, the Cyclomatic Complexity number is not incremented, whereas it is incremented when the structure is outside a f-string. See the following examples.

The next code snippet has a complexity of 1 (base value), which is incorrect:

def function1():
    return f"{', '.join(['Earth!' for _ in range(10)])}"

Removing the f-string results in the correct value of 2:

def function1():
    return ', '.join(['Earth!' for _ in range(10)])}