radon
radon copied to clipboard
Feature request: Cognitive complexity.
Hi. First of all, thanks for your work. I wonder if anybody interested in implementing the calculation of Cognitive complexity alongside with Cyclomatic complexity. More info: https://www.sonarsource.com/docs/CognitiveComplexity.pdf
@happy4upa Thanks for sharing the paper, it was an interesting read!
Currently I do not have time to implement a new metric. But if you want to give it a go, I'll be happy to review a PR. Essentially, what is needed is the following:
- a new visitor in
radon.visitorsthat correctly counts cognitive complexity - a new function in
radon.cli.__init__that implements the CLI for this metric - (possibly) an helper function in
radon.complexity - tests for all the new code
- a few paragraphs in the documentation about the new metric
I'm very interested in implementing this metric. I do start working in my fork, but couldn't grasp the whole point of metric in relation to Python. If anyone want to collaborate, i'll be very appreciated.
@tribals I think you can start by cloning the ComplexityVisitor and incrementing the cognitive complexity score on these elements:
- if/elif/else
- for/while
- break/continue
- try/except
- recursion calls
- mixed boolean operators
That should be reasonably easy and we could already add the basic tests. Then the final part needs to be implemented: the nesting increments. When any of the above statements is found, you don't just increase the score by 1, but also by the nesting level. Then we can also add tests similar to the paper examples.
Some things mentioned in the paper don't apply to Python (do-while loops, switch, goto, etc.), but I'd say the general idea is still extremely interesting. Intuitively, one can see that a function with many nested levels is more complicated than a plain one. While cyclomatic complexity focuses on the number of code paths, cognitive complexity is closely related to readability and maintainability and its rules are applicable to Python too.
A python library to compute the cognitive complexity is available in: https://github.com/Melevir/cognitive_complexity
There is also a plugin for flake8: https://pypi.org/project/flake8-cognitive-complexity/
I am not sure if this should be incorporated into radon. or if that should be left to the above tools.
Thanks @cleder. I think @tribals can incorporate some of those ideas into Radon.