ruff: Implement `flake8-cognitive-complexity`
-
CCR001: Cognitive complexity is too high (X > Y)
Configuration options: max-cognitive-complexity
This plugin is focused on cognitive complexity vs cyclomatic complexity which we have via mccabe. Apparently this is the algorithm used by SonarSource, CodeClimate, etc. according to the README. See here for more details.
About this issue
- Original URL
- State: open
- Created 4 years ago
- Reactions: 53
- Comments: 17 (7 by maintainers)
I was looking to replace my
flake8plugins list withruffand there’s 2 plugins I couldn’t replace yet:flake8-cognitive-complexityflake8-expression-complexityHope to see them implemented in ruff.
I always include cyclomatic + expression + cognitive.
Here a quick example which demonstrate each complexity:
fooWould be the best option if we only looks for Cyclomatic complexity.
But the expression is complex, especially for a junior developer or someone who just start with Python.
The Cognitive represent, as I interpret it myself, the amount of context you have to store in your brain.
barWould be the worst option if we only looks for Cyclomatic complexity.
But the expression is simple, each line is easy to understand.
You could need a higher level of context storage in your brain as you analyse this code, which is why it give a higher Cognitive complexity.
boousingsubbooCyclomatic complexity is reduce compare to
barbut still higher thanfoo.Max Expression is the same than
bar.The Cognitive complexity is at 2, each function is pretty simple to analyze without the need to keep too much context in your brain.
FWIW,
flake8-cognitive-complexityandflake8-cohesionare the only two rules I still run. If those were added to Ruff, I could fully removeflake8from my project.I do run McCabe in Ruff as well, but they serve three different purposes, IMHO.
Hi @MichaReiser! I’m a big fan of the rule proposed in this issue, I’m curious have you/the astral team done any of the design work here/is this included in a product roadmap in any way?
Hello! Is there any traction to have this implemented in ruff?
Cognitive complexity is how hard the code is to understand, while cyclomatic complexity is the number of independent branches. For example, a switch case that handles every letter of the alphabet might be very easy to understand, but it would have 26 separate branches.
Anyone want to look at my PR? #9812
Didn’t know that one, thanks for sharing 😉
Also in the same terms it would be nice to implement
flake8-cohesionI usually have all enabled, unless they are exact duplicates, of course…
It’d be also nice to implement https://github.com/Miserlou/JonesComplexity that WPS uses, for example…
Ah, I see your point! The main reason I run McCabe is because I don’t want to run flake8 in Github Actions for just a single rule. I personally wouldn’t mind replacing it.
However, I do find unique benefit from the related flake8-cohesion, which looks at a class as a whole.