Radon - Keep your Code Easy to Understand
Writing code can be difficult, writing simple code can be even harder. To ensure you don’t get carried away you can use one of the many tools to assess the “quality” of labour.
radon is a very useful tool for peer reviewing your code. It has three modes performing analysis of your code that we will touch on below.
cc - Compute Cyclomatic Complexity
Cyclomatic complexity is a software metric, used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program’s source code. but for a quick start to the following:
Here we use it to get a rough grading of our python file, A is good, all the way down to E which as you might expect is bad.
$ radon cc my-package my-package/complex_module/awesome/ness.py F 178:0 format_monkey_tree - B M 111:4 MonkeyNode.validate - B M 153:4 MonkeyNode.__eq__ - B F 205:0 build_monkey_tree - B M 56:4 MonkeyNode.__init__ - A F 240:0 iter_critical_errors - A M 75:4 MonkeyNode.new_value - A M 95:4 MonkeyNode.has_critical_errors - A M 101:4 MonkeyNode.iter_monkeys - A M 106:4 MonkeyNode.iter_nodes - A M 166:4 MonkeyNode.__ne__ - A M 172:4 MonkeyNode.__repr__ - A C 31:0 InvalidatingMonkeyError - D M 32:4 InvalidatingMonkeyError.__init__ - D C 37:0 MissingMonkeyError - A M 38:4 MissingMonkeyError.__init__ - A my-package/complex_module/service.py C 17:0 MonkeyCalculator - A M 31:4 MonkeyCalculator.healthyness - A
The above is the output from a fictional project. The filename is on the right and the rating is the letter after
-. It’s not bad overall, mostly
As with a few
Ds thrown in.
Low ratings are an indicator of complex which has the potential to cause issues with maintenance and development issues later in the life of the project.
The output gives you a list of priorities for you refactoring.
raw - Raw Statistics
$ radon raw my-package my-package/__init__.py LOC: 1 LLOC: 1 SLOC: 1 Comments: 1 Single comments: 0 Multi: 0 Blank: 0 - Comment Stats (C % L): 100% (C % S): 100% (C + M % L): 100% my-package/complex_module/service.py LOC: 529 LLOC: 175 SLOC: 348 Comments: 27 Single comments: 30 Multi: 61 Blank: 90 - Comment Stats (C % L): 5% (C % S): 8% (C + M % L): 17%
mi - Maintainability Index
$ radon mi my-package runner/__init__.py - A my-package/complex_module/service.py - A