McCabe-style cyclomatic complexity in Python code

by

Cyclomatic complexity is a software metric for measuring source code complexity by analyzing the number of linearly independent paths through a function (or full program). This meassure corresponds to the effort needed to do a full path by path test of the code. If such tests are not done (which – without automation – clearly will be the case for pieces of code with large number of paths) it will be degraded to a nice indicator for the trustworthiness of the code.

Such a complexity analyser has been written for python (in perl). The files has to be saved under the correct names (complexdef, complexdefclass, complexity and tab) and made executable.

One of these scripts depends on ksh. This is not part of a default Ubuntu Gutsy Gibbon installation but can easely be added by running:

sudo apt-get install ksh

Another issue seems to be that the perl syntax for the sort function has evolved, so that lines of the form

open (T,"|$dn/tab|sort -n +5") || die "no tab?";

has to be changed to

open (T,"|$dn/tab|sort -n -k 5") || die "no tab?";

This issue is present once in complexdef and twice in complexdefclass. For some reason there seems to be a syntax error in the definition of the usage function of the tab file. Replacing from the ‘sub usage {' line to the end with the following seems to be working:

sub usage {
print “dummy value\n”;
}

A nice wrapper script has been written in python. When this is configured (by changing PATH_TO_COMPLEXITY) it can be run by

./complexity.py PATH_TO_PY_FILES

Leave a comment